aspose file tools*
The moose likes Java in General and the fly likes Accessing instance members in constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Accessing instance members in constructors" Watch "Accessing instance members in constructors" New topic
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: 149
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing instance members in constructors
 
Similar Threads
Accessing instance members before the super constructor completes
Answer: for Topic: Question abt inheritance.. [phani ] [Topic closed without solution
Automatically populate instance variables
Constructor doubt