Java Instance Initializer Block: Definition and Usage

Rumman Ansari   Software Engineer   2024-07-04 03:44:43   7173  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Initializer block contains the code that is always executed whenever an instance is created. Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. It also It isto declare/initialize the common part of various constructors of a class. The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the Instance Initializer block.

We can directly assign a value in instance data member

For example:
class Animal{  
    String name= "Cow" ; 
}  

Why instance initializer block is important ?

To perform some operations while assigning value to instance data member

Example of instance initializer block

Let's see the simple example of instance initializer block the performs initialization.

Program:
class Animal{
    int age;

    Animal(){
		System.out.println("age is "+age);
		}

    {age=10;}

    public static void main(String args[]){
    Animal b1=new Animal();
    Animal b2=new Animal();
    }
}
Output:
age is 10
age is 10
Press any key to continue . . .
Program:
public class InitializerBlock
{
    // Initializer block starts..
    {
        // This code is executed before every constructor.
        System.out.println("Common part of constructors invoked !!");
    }
    // Initializer block ends

    public InitializerBlock()
    {
        System.out.println("Default Constructor invoked");
    }
    public InitializerBlock(int x)
    {
        System.out.println("Parametrized constructor invoked");
    }
    public static void main(String arr[])
    {
        InitializerBlock obj1, obj2;
        obj1 = new InitializerBlock();
        obj2 = new InitializerBlock(0);
    }
}
Output:
Common part of constructors invoked !!
Default Constructor invoked
Common part of constructors invoked !!
Parametrized constructor invoked
Press any key to continue . . .

We can note that the contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents)
The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor.

There are three places in java where you can perform operations:
  1. method
  2. constructor
  3. block

What is invoked first, instance initializer block or constructor?

Program:
class Animal{
    int speed;

    Animal(){
		System.out.println("constructor is invoked");
		}

    {System.out.println("instance initializer block invoked");}

    public static void main(String args[]){
    Animal b1=new Animal();
    Animal b2=new Animal();
    }
}
Output:
instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
Press any key to continue . . .

The java compiler copies the instance initializer block in the constructor after the first statement super(). In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. So firstly, constructor is invoked.

Rules for instance initializer block :

There are mainly three rules for the instance initializer block. They are as follows:
  1. Initialization blocks execute in the order they appear.
  2. The instance initializer block is created when an instance of the class is created.
  3. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call). i.e- Instance Initialization blocks run after the constructor's call to super().
  4. Instance Initialization blocks run every time a class instance is created.
  5. Static Initialization blocks run once when the class is first loaded.

Order of execution:

  1. The constructor of the class.

  2. static initialization blocks of super classes

  3. static initialization blocks of the class

  4. instance initialization blocks of super classes

  5. constructors of super classes

  6. instance initialization blocks of the class

Program of instance initializer block that is invoked after super()

Program:
class Animal{
Animal(){
	System.out.println("Animal parent class constructor invoked");
	}
}

class Cow extends Animal{
	Cow(){
	super();
	System.out.println("child class Cow constructor invoked");
}

{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){
	Cow b=new Cow();
	}
}
Output:
Animal parent class constructor invoked
instance initializer block is invoked
child class Cow constructor invoked
Press any key to continue . . .

Another important example of instance block

Program:
class Animal{
	Animal(){
		System.out.println("Animal parent class constructor invoked");
		}
}

class Cow extends Animal{
		Cow(){
		super();
		System.out.println("Cow child class invoked");
}

Cow(int p){
	super();
	System.out.println("Cow child class constructor invoked "+p);
}

{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){
	Cow c1=new Cow();
	Cow c2=new Cow(10);
	}
}
Output:
Animal parent class constructor invoked
instance initializer block is invoked
Cow child class invoked
Animal parent class constructor invoked
instance initializer block is invoked
Cow child class constructor invoked 10
Press any key to continue . . .

Remember:

Instance initializer block is a mechanism provided by java compiler to define a group of statements common to all constructors at a single place. At the compilation time, compiler moves these statements at the beginning of all constructors after super(). It is can also be used to initialize the instance variable.

Program:
/**
 * This program is used to show the use of AnonymousBlock.
 * @author atnyla Developer
 */
class Display {
      int a, b;

      //Anonymous or instance initializer Block
      {
          System.out.println("AnonumousBlock called.");
          a = 10;
      }

     //default constructor
     Display(){
        System.out.println("default constructor called.");
     }

     //one argument constructor
     Display(int num){
        System.out.println("one parameter constructor called.");
        b = num;
     }

     //method to display values
     public void display(){
            System.out.println("a = " + a);
            System.out.println("b = " + b);
     }
}

public class AnonymousBlockExample1 {
       public static void main(String args[]){
              Display obj1 = new Display();
              obj1.display();

              Display obj2 = new Display(20);
              obj2.display();
       }
}
Output:
AnonumousBlock called.
default constructor called.
a = 10
b = 0
AnonumousBlock called.
one parameter constructor called.
a = 10
b = 20
Press any key to continue . . .

If two Anonymous Blocks are used then they will execute in the same order in which they are appear.

Program:
/**
 * This program is used to show that if two AnonymousBlocks
 * are used then they will execute in the same order in
 * which they are appear.
 * @author atnyla developer
 */
class Display {
      int a, b, c;

      //First Anonymous or instance initializer Block
      {
         System.out.println("First AnonumousBlock called.");
         a = 15;
      }

      //Second Anonymous or instance initializer Block
      {
          System.out.println("Second AnonumousBlock called.");
          b = 25;
      }

      //default constructor
      Display(){
          System.out.println("default constructor called.");
      }

      //one argument constructor
      Display(int num){
              System.out.println("one parameter constructor called.");
              c = num;
     }

     //method to display values
     public void display(){
            System.out.println("a = " + a);
            System.out.println("b = " + b);
            System.out.println("c = " + c);
     }
}

public class AnonymousBlockExample1 {
       public static void main(String args[]){
              Display obj1 = new Display();
              obj1.display();

              Display obj2 = new Display(30);
              obj2.display();
       }
}
Output:
First AnonumousBlock called.
Second AnonumousBlock called.
default constructor called.
a = 15
b = 25
c = 0
First AnonumousBlock called.
Second AnonumousBlock called.
one parameter constructor called.
a = 15
b = 25
c = 30
Press any key to continue . . .

If static and non-static Anonymous Blocks are used then static Anonymous Block is executed only once.

Program:
/**
 * This program is used to show that if static and non-static
 * AnonymousBlocks are used then static AnonymousBlocks is
 * executed only once.
 * @author atnyla developer
 */
class Display {
      int a, b;

      //static Anonymous or instance initializer Block
      static {
              System.out.println("Static AnonumousBlock called.");
      }

      //non-static Anonymous or instance initializer Block
      {
          System.out.println("Non-Static AnonumousBlock called.");
          a = 10;
      }

      //default constructor
      Display(){
          System.out.println("default constructor called.");
      }

      //one argument constructor
      Display(int num){
         System.out.println("one parameter constructor called.");
         b = num;
      }

      //method to display values
      public void display(){
             System.out.println("a = " + a);
             System.out.println("b = " + b);
     }
}

public class AnonymousBlockExample1 {
       public static void main(String args[]){
              Display obj1 = new Display();
              obj1.display();

              Display obj2 = new Display(30);
              obj2.display();
      }
}
Output:
Static AnonumousBlock called.
Non-Static AnonumousBlock called.
default constructor called.
a = 10
b = 0
Non-Static AnonumousBlock called.
one parameter constructor called.
a = 10
b = 30
Press any key to continue . . .

In which order static initializer block, instance initialize block, super and constructor are called?

static initialize block –> super-> instance initialize block –> constructor.

Program:
/**
 * This program is used to show that in which order static
 * AnonumousBlocks, non-static AnonumousBlocks, super and
 * default constructors are called.
 * @author atnyla developer
 */
class Show{
      Show(){
             System.out.println("Super class constructor.");
      }
}

class Display extends Show{
      //static Anonymous or instance initializer Block
      static {
              System.out.println("Static AnonumousBlock called.");
      }

      //non-static Anonymous or instance initializer Block
      {
        System.out.println("Non-Static AnonumousBlock called.");
      }

      //default constructor
      Display(){
           super();
           System.out.println("default constructor called.");
      }
}

public class AnonymousBlockExample1 {
       public static void main(String args[]){
               Display obj = new Display();
       }
}

Output:
Static AnonumousBlock called.
Super class constructor.
Non-Static AnonumousBlock called.
default constructor called.
Press any key to continue . . .