It's not a secret anymore!
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

Constructor invocation order

ZahidM Khan

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

Joined: Jan 28, 2003
Posts: 4181

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

Robert Simmons Jr.

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
ZahidM Khan

Joined: Apr 06, 2012
Posts: 8
Thank you Steve.
I agree. Here's the link:
subject: Constructor invocation order
It's not a secret anymore!