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