Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor initialization

 
cornel jew
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
What i understand from inheritance is that the base class is first initialise b4 the sub.
Why is it that the following code is accessing the overriden method from sub instead of base when calling from base constructor.
To me the subclass is not initialise yet,but still it access that method.
I need some clarity.
Thanks for your help.
class Base
{
void B(){System.out.println("B() method in Base ");}
void A(){System.out.println("A() method in Base ");
B();}
Base(){System.out.println("Base constructor");
A();
}
}
public class Sub extends Base
{
void A(){System.out.println("A() method in Sub ");
B(); }
void B(){System.out.println("B() method in Sub ");}
public static void main(String args[])
{
new Sub();
}
}
 
Sonny Gill
Ranch Hand
Posts: 1211
IntelliJ IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about it this way,
when an object is created, it contains the type-information that indentifies what type(class) it is. So, even thought you are calling that method from the base class constructor, JVM knows what type it REALLY is, and used the late binding to call the subclass method.
Hope that helped. Experiment with making that method static or private, think about why it shows different behaviour then
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is one of those not so pretty Java gotchas.
cornel, I agree that it just seems odd to be able to call a method of an object that would seem to not yet be fully initialized - but you can. For example, this obnoxious program:displays 0 when 2 were perhaps expected.

To be safe, just never call an overridable (that may not be a real word) method from a constructor (make those initializing methods private).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic