by BehindJava

What is Instance Initializer block in Java

Home » java » What is Instance Initializer block in Java

In this tutorial we are going to learn about Instance Initializer block which is used to initialize the instance data member i.e. run at each time when object of the class is created.

A static initializer is the equivalent of a constructor in the static context. which is needed to setup the static environment. A instance initializer is best for anonymous inner classes.

It is also possible to have multiple initializer blocks in class When we have multiple initializer blocks they are executed (actually copied to constructors by JVM) in the order they appear.

Order of initializer blocks matters, but order of initializer blocks mixed with Constructors doesn’t

Abstract classes can also have both static and instance initializer blocks.

Sample Code Snippet:

abstract class Aircraft {
    protected Integer seatCapacity;
    {   // Initial block 1, Before Constructor
        System.out.println("Executing: Initial Block 1");
    }
    Aircraft() {
        System.out.println("Executing: Aircraft constructor");
    }

    {   // Initial block 2, After Constructor
        System.out.println("Executing: Initial Block 2");
    }

}

class SupersonicAircraft extends Aircraft {
    {   // Initial block 3, Internalizing a instance variable
        seatCapacity = 300;
        System.out.println("Executing: Initial Block 3");
    }
    {   // Initial block 4
        System.out.println("Executing: Initial Block 4");
    }
    SupersonicAircraft() {
        System.out.println("Executing: SupersonicAircraft constructor");
    }
}

An instance creation of SupersonicAircraft will produce logs in below order

Output:

Executing: Initial Block 1
Executing: Initial Block 2
Executing: Aircraft constructor
Executing: Initial Block 3
Executing: Initial Block 4
Executing: SupersonicAircraft constructor

Points to Remember:

Instance Initialization Blocks run every time a new instance is created. Initialization Blocks run in the order they appear in the program. The Instance Initialization Block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).