| Author |
Accessing instance members in constructors
|
Mac Sta. Maria
Greenhorn
Joined: Aug 11, 2012
Posts: 8
|
|
I read in K&B6 that instance members are accessible only after the super constructor runs.
I stumbled upon the following code:
and it prints:
My question would be:
If instance members are accessible only after the super constructor runs, then why is it that upon execution of the printIt( ) method of class Parent, (which in fact is Child's printIt( ) due to polymorphism), it was able to access the uninitialized instance variable i of Child even though the constructor of Parent has not yet finished executing?
Confused here. What am I missing?
|
 |
Don Redd
Ranch Hand
Joined: Jan 05, 2012
Posts: 82
|
|
|
rather than using word "Accessing", you can say "initialized", the instance variables are initialized after super constructor finishes and before completion of rest of its own(this) constructor.
|
 |
s ravi chandran
Ranch Hand
Joined: Dec 20, 2010
Posts: 127
|
|
|
I believe object creation is a two step process. Firstly, the declared variables are processed by the compiler, then the second step involving calling of super constructors up in the hierarchy. after the initialization from all the super classes, the current instance value should be assigned.
|
 |
Mac Sta. Maria
Greenhorn
Joined: Aug 11, 2012
Posts: 8
|
|
Thank you all for clarifying. Makes sense now.
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
same as
in this context this means Child object.
|
 |
 |
|
|
subject: Accessing instance members in constructors
|
|
|