| Author |
Overridden method invoked in the constructor. Please clear it for me.
|
L. Wei
Ranch Hand
Joined: May 01, 2008
Posts: 37
|
|
The output is: AAA Bvar=0 ( I am confused over here.) BBB Bvar=2222 Avar=0 Why B.doSomething() is invoked in Class A's constructor? Please clear it for me.
|
SCJP SE 6.0, SCWCD J2EE 5
|
 |
Ninad Kulkarni
Ranch Hand
Joined: Aug 31, 2007
Posts: 774
|
|
Bvar is initially initialized to zero but variable initializer is happen after super class object is created I will give you sequence of execution 1 class loading 2 class initialization first super class and then sub class 3 static inialization or static variable initialization from super then sub class 4 then main of sub invokes 5 then call to super()due to new B()but Bvar initialized to default value no instance variable initialization happens at this time 5 before A() runs all inastance of A are initialized doSomething of B is called at that time Bvar is having only default value of 0 6 then control go to B() at this time Bvar is happen to 2222 before B() runs 7 in B() printing of BAvr which got value of 2222 I think you should know this execution process for understaing then you got why Bvar = 0 in output of program I hope this may help you If I am wrong somewhere in explaination please notify me about that regards Ninad
|
SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
|
 |
L. Wei
Ranch Hand
Joined: May 01, 2008
Posts: 37
|
|
Thanks Ninad. I know the sequence of execution. Actually, what is confusing me is not the assignment of Bvar. I am confused why the doSomething() in the class B is invoked in the constructor of A. My original answer to the question is, AAA A.doSomething() (The right answer is Bvar=0, I am confused) BBB Bvar=2222 Avar=0 You mentioned "doSomething of B is called at that time". Can you tell me why?  [ June 18, 2008: Message edited by: David L. Wei ]
|
 |
Ninad Kulkarni
Ranch Hand
Joined: Aug 31, 2007
Posts: 774
|
|
Because doSomething() method is overriden in sub class B and we have instatiated class B instance method selection is done at runtime in overriding instance variable selection is done at compile time A() constructor calls B's doSomthing() method because we have done new B() not new A() you can do new A() and see what happens you may get AAA A.doSomthing() constructor of A() select doSomething() method of class A not of class B I hope this may help you Regards Ninad
|
 |
 |
|
|
subject: Overridden method invoked in the constructor. Please clear it for me.
|
|
|