When does the Constructor gets called in java?

At the byte code level.

  1. An object is created but not initialised.
  2. The constructor is called, passing the object as this
  3. The object is fully constructed/created when the constructor returns.

Note: The constructor at the byte code level includes the initial values for variables and the code in the Java constructor. e.g.

int a = -1;
int b;

Constructor() {
   super();
   b = 2;
}

is the same as

int a;
int b;

Constructor() {
   super();
   a = -1;
   b = 2;
}

Also note: the super() is always called before any part of the class is initialised.


On some JVMs you can create an object without initialising it with Unsafe.allocateInstance(). If you create the object this way, you can't call a constructor (without using JNI) but you can use reflections to initialise each field.


The object memory is allocated, the field variables with initial values are initialized, and then the constructor is called, but its code is executed after the constructor code of the object super class.

Tags:

Java