I'm not sure, since you haven't pointed how the results confuse you, but I'm guessing it's the same as the thread here. You can also use the UBB CODE tags to format code. Dave
Joined: Jan 08, 2004
The result I got from running this program was: amethod in Y 10 amethod in Y This was not what I expected though. Maybe I'm overlooking some wierd polymorphism rule here? I thought the results would be: amethod in X 10 amethod in Y My question is why the first result happens and not the second (the one I expected). Its clear that when a new object of type Y is being created, in its constructor it calls its superclass constructor. But, in the superclass constructor, why does it not use the amethod defined in the superclass instead of the one defined in the derived class? I hope that makes my issue a bit more clear. Thanks, Cliff
I checked the Java Language Spec in relation to instance creation (refer to section 12.5). To quote:
Unlike C++, the Java programming language does not specify altered rules for method dispatch during the creation of a new class instance. If methods are invoked that are overridden in subclasses in the object being initialized, then these overriding methods are used, even before the new object is completely initialized.
It then gives an example similar to yours showing that even though you are in a constructor, there is an implied "this" which is an instance of class "Y", so that classes method is invoked. It was a decision made early on and it works that way because the creators of Java explicitly specified it to be so.
Originally posted by Cliff DeRose: The result I got from running this program was: amethod in Y 10 amethod in Y Thanks, Cliff
This is because of late binding. When you create delare myX as as X but then define myX as new Y, java compiler doesn't do the binding (that would be early binding). It gets resolved at run time; at run time it checks to see the type of object myX is & then calls the constructor of Y.
Ever Existing, Ever Conscious, Ever-new Bliss
Joined: Jan 08, 2004
Thanks very much, it is much more clear now. Seems like just the kind of a sneeky question that would appear on the sun certified java programmer exam. Cliff