wood burning stoves 2.0*
The moose likes Java in General and the fly likes Constructor invocation order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Constructor invocation order" Watch "Constructor invocation order" New topic
Author

Constructor invocation order

ZahidM Khan
Greenhorn

Joined: Apr 06, 2012
Posts: 8
According to my understanding we invoke constructor to create an object, on constructor invocation if we don't assign explicit value to instance variables then it would be initialized to default values.

I just got confused after reading this statement in a book The Java Programming Language which says
Constructors are invoked after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializers are executed.


Please can someone elaborate whether we invoke constructor first and then instance variables get initiated to explicit/default value or is it other way around?
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4165
    
  21

Well, first, a Constructor does not create an object. You use the new operator to create a new Object, and it picks and executes the Constructor which closest matches the signature. But executing the constructor is not the first thing it does. The new operator works mostly like this:
1) determines which Constructor to execute
2) process the constructor's parameters
3) create an Object for the instance
4) construct the superclass
5) initialize the instance properties for the Object
6) execute the Constructor

So the initialization occurs before the constructor body is executed.

For more: See JLS 12.5


Steve
Robert Simmons Jr.
Author
Greenhorn

Joined: May 26, 2004
Posts: 2

To answer the initial question, instance variable initializers are run before the body of the constructor.


-- Robert Simmons Jr.

Author: Maintainable Java
http://www.amazon.com/Maintainable-Java-ebook/dp/B00AKHI69K/ref=sr_1_2?ie=UTF8&qid=1355159024&sr=8-2&keywords=Maintainable+Java
ZahidM Khan
Greenhorn

Joined: Apr 06, 2012
Posts: 8
Thank you Steve.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructor invocation order
 
Similar Threads
Static Blocks and Instance Initializers (on certification exam?)
Instantiation/Forward referencing
initilizer expressions
Can not call explicit Constructor
this(i)