1

in MainFrameclass there is a method named createPerson which takes String id and returns Person type.

and in my Person class there is a method getFatherName which returns a string.

in my Tree class can I do the following statement ?:

String father = ( MainFrame.createPerson("001") ).getFatherName();

can i do this without creating an instance of MainFrame?

edit: i cannot create an instance of MainFrame it is a main class with GUI

Mustafa
  • 592
  • 8
  • 17

2 Answers2

1

Sure you can! If the method MainFrame.createPerson() is defined as a static/class method.

You are probably already familiar with static methods, without knowing it, like the methods in Math class or System.exit()

These are often used as factory methods, which seems to be the case in here.

amit
  • 175,853
  • 27
  • 231
  • 333
-1

That will only work if MainFrame is a static class. Otherwise you will need to create an instance of MainFrame. You can create the instance inline thought like this:

String father = ( new MainFrame.createPerson("001") ).getFatherName();
hav2play21
  • 171
  • 7
  • 1
    `if MainFrame is a static class` What is a static class in java? There is only static inner class, and it has nothing to do with this. – amit May 10 '12 at 19:39
  • 1
    You need parentheses after the constructor name. – Mike Samuel May 10 '12 at 19:41
  • Here is an example of how java does Static classes: http://stackoverflow.com/questions/3584113/java-static-class. If you are unable to do an inner class then you will need to create a new object of type MainFrame. – hav2play21 May 10 '12 at 19:42
  • 2
    @hav2play21: Indeed, it is a static inner class, and the top answer there says: `Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.`. It has nothing to do with the case here. – amit May 10 '12 at 19:50
  • 1
    "That will only work if" `createPerson` is a static _method_. Otherwise the example, `= new MainFrame().createPerson("001").getFatherName();` works _if_ there's a public constructor. The term "static class" is _sometimes_ used, very informally, as on this page, to mean a class with all static methods and a private constructor (so no instance can be created.) – RalphChapin May 10 '12 at 20:41