Hola, Function calls are polymorphic--the most specialized class will handle the method call. In this case it is the SubClass implementation of printNum. Now here's the trick: all superclass constructors have to return before the subclass constructors do. That means that "num" won't actually be 5 until SuperClass's constructor returns and SubClass's instance variables are correctly initialized. So, while SuperClass's constructor is doing it's thing, num is 0! SuperClass.printNum will invoke SubClass.printNum, which prints out the current value of num--0. After that, SubClass finishes being constructed and num is finally set to 5, after which another call to printNum actually prints out 5. Does that make any sense?
Nathaniel, Could you please explain more on why the constructor of the superclass calls the printNum method of SubClass and not it's own printNum method? I have one more question. Would it make any difference if the following declaration : SuperClass t = new SubClass(); was replaced by this declaration : SubClass t = new SubClass(); Thanks, Ruchi.
Originally posted by Ruchi Sharma: Could you please explain more on why the constructor of the superclass calls the printNum method of SubClass and not it's own printNum method? I have one more question. Would it make any difference if the following declaration : SuperClass t = new SubClass(); was replaced by this declaration : SubClass t = new SubClass();
First of all, the reason it invokes the method in SubClass is because the method is overridden. As the object is question is really of type SubClass, we'll invoke SubClass.printNum(), rather than SuperClass.printNum(). You can check out the JLS, §15.12.4 Runtime Evaluation of Method Invocation, for more information, but it's not the easiest read in the world. You can also do a search over this forum about polymorphism. As for your secodn question, it would make no difference. The parent class must be initialized prior to initialization of the child class so the constructor of SuperClass would still be invoked and the output would be identical. Try it and see. Corey
Methods are dispatched polymorphically. The most specialized class that has a definition for a method will be the one that gets invoked. It is not different from the fact that Object defines "equals", but all other classes will override "equals", too, in order to be sorted and so forth. The real catch in this case is the fact that the variable won't be initialized to 5 until the superclass constructor finishes.
Joined: Mar 24, 2004
Thanks Corey and Nathaniel! It does make sense now. Ruchi.