Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor invocation order

 
ZahidM Khan
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Author
Greenhorn
Posts: 2
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To answer the initial question, instance variable initializers are run before the body of the constructor.
 
ZahidM Khan
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Steve.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic