The sequence of events when a new object is instantiated via the new operator (known as the instantiation process) is as follows:
JVM allocates memory for the instance in the help.
JVM initializes the instance variables to their assigned values or default values.
JVM invokes the constructor.
The first statement of the constructor is always a call to its immediate superclass’ constructor. JVM invokes the selected superclass’ constructor.
JVM executes the instance initializers in the order of appearance.
JVM executes the body of the constructor.
The new operator returns a reference to the new object.
For example,:
public class Hello {
private int number1 = 11; // explicit initializer
{ // instance initializer
number1 = 99;
number2 = 88;
}
private int number2 = 22; // explicit initializer
public Hello() { }
public Hello(int number1, int number2) { // Constructor
this.number1 = number1; // Run after initializers
this.number2 = number2;
}
public static void main(String[] args) {
Hello h = new Hello();
System.out.println("number1 is " + h.number1); // 99
System.out.println("number2 is " + h.number2); // 22
Hello h2 = new Hello(55, 66);
System.out.println("number1 is " + h2.number1); // 55
System.out.println("number2 is " + h2.number2); // 66
}
}