Java object initialization and instantiation order

Java object initialization and instantiation order

Initialization means to provide value for the instance members and instantiation means to construct the object.
During instantiation the order from parent to child class is always maintained.

 

Sequence

  • The default value of the instance member is assigned to the instance member.
  • Super is called from the constructor.
  • Initializer method or the value the field needs to be assigned is executed.
  • Instance initializer block is executed.
  • Rest of the constructor code is executed.
  • Do remember call to super in 2 step means all the sequence is applied on parent class first and then the child class.
  • Sequencing of initializer block or initializer method do-sent matter , the execution sequence will be the same.

 

Code:


package com.big.data.java.samples;

class SuperClass {
    int b;

    public SuperClass(int c) {
        this.b = c;
        System.out.println("I am inside super class Constructor  :   " + b);
    }
}

public class SubClass extends SuperClass {

    private String state = initializerMethod();

    public SubClass() {
        super(1);
        System.out.println("I am inside Constructor");
        System.out.println("value of state inside Constructor, before is  : " + state);
        state = "constructor";
        System.out.println("value of state inside Constructor, after  is  : " + state);
    }

    private String initializerMethod() {
        System.out.println("I am inside instance Method initialize ");
        return "method Initializer";
    }

    {
        System.out.println("I am inside instance initialize Block");
        System.out.println("value of state inside initializer Block is " + state);
        state = "initializer Block";
    }

    public static void main(String[] args) {
        SubClass reference = new SubClass();
    }

}

[addToAppearHere]

Sequence :

  • state = null;
  • super() called
  • initializer Method() called
  • initializer block executed
  • Constructor resumed.
  • Sequencing of initializer block or initializer method do-sent matter , the execution sequence will be the same.

 

OutPut

I am inside super class Constructor : 1
I am inside instance Method initialize
I am inside instance initialize Block
value of state inside initializer Block is method Initializer
I am inside Constructor
value of state inside Constructor, before is : initializer Block
value of state inside Constructor, after is : constructor