×

Java Programs

Java Practice

Java program to create multiple Instance Initializer Block

Learn how to create multiple Instance Initializer Block in Java?
Submitted by Nidhi, on March 25, 2022

Problem statement

In this program, we will create multiple Instance Initializer Block in a class. The IIB (Instance Initializer Block) is called when an object is getting created.

Java program to create multiple Instance Initializer Block

The source code to create multiple Instance Initializer Block is given below. The given program is compiled and executed successfully.

// Java program to create multiple Instance 
// Initializer Block

class Sample {
  {
    System.out.println("IIB1 called");
  }

  {
    System.out.println("IIB2 called");
  }

  Sample() {
    System.out.println("Constuctor called");
  }

  {
    System.out.println("IIB3 called");
  }
}

public class Main {
  public static void main(String[] args) {
    Sample S = new Sample();
  }
}

Output

IIB1 called
IIB2 called
IIB3 called
Constructor called

Explanation

In the above program, we created two classes Sample and Main. The Sample class contains three IIB (Instance Initializer Block) and a constructor.

In the above program, it looks like IIB is calling before the constructor. But it is not true. IIB gets called when an object is created. Java compiler copies the IIB in the constructor after the first statement super(). So constructor calls the IIB.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of the Sample class and printed the appropriate message.

Java Instance Initializer Block Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.