File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Constructor initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Constructor initialization" Watch "Constructor initialization" New topic

Constructor initialization

cornel jew
Ranch Hand

Joined: Jul 13, 2002
Posts: 37
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 ");
Base(){System.out.println("Base constructor");
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

Joined: Feb 02, 2002
Posts: 1211

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

The future is here. It's just not evenly distributed yet. - William Gibson
Sonny Gill LinkedIn
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
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).

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Constructor initialization
It's not a secret anymore!