This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
I am not good at this much. I can't figure it out. But if you didn't over ride the method1 at BB class it would print "a".
Joined: Sep 17, 2011
Rumesh Eranga wrote:I am not good at this much. I can't figure it out. But if you didn't over ride the method1 at BB class it would print "a".
I could figure out it.
Instance variables are instantiated after all of its constructors are completed. Here I create new BB object
'BB b = new BB();' It calls BB's default constructor and then AA's no-arg constructor. Within AA constructor it calls another method 'method1' which is in BB class.
At this time AA's constructor completes and assigns values to the 'a' and 'b'(in AA class). Since constructor of AA calls a method in BB, constructor of BB is not completed. So there are no any value for 'a' in class BB.
Since this is a String it has its default value null.
The result of the above code is 'null'. I cannot understand why it results a null.
Can anyone explain >>
The order of instantiation is... The super() part of the constructor is executed. The instance variables (and instance initializers) are initialized in order that they were defined in the class. And finally, the rest of the constructor is executed.
This means.... the instance variable for the BB class has not been instantiated at the time the constructor for AA is called.
So.... when the AA constructor calls the method1() method, which due to polymorphism, calls the method1() method of the BB class, the instance variables of the BB class has not been initialized yet.
More Clearly in Super and Sub class relationship :
Say constructor of Child is called
constructor of Super class is called by Child class constructor.
Instance member are initialized , in specified order.
constructor of Super class completes.
Instance member of Sub class gets initialized, in specified order. .
constructor of Sub class completes.