Forums Register Login

Overridden method invoked in the constructor. Please clear it for me.

+Pie Number of slices to send: Send


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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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
It will give me the powers of the gods. Not bad for a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 848 times.
Similar Threads
Please help me.......
why this happend in constructor?
constructors
difficult Construction
constructors
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:19:44.