×

Java Programs

Java Practice

Java program to call an Instance Initializer Block using the anonymous object

Learn how to call an Instance Initializer Block using the anonymous object in Java?
Submitted by Nidhi, on March 25, 2022

Problem statement

In this program, we will create a class with Instance Initializer Block and constructor. Then we will create the anonymous object to call IIB and constructor.

Java program to call an Instance Initializer Block using the anonymous object

The source code to call an Instance Initializer Block using an anonymous object is given below. The given program is compiled and executed successfully.

// Java program to call an Instance Initializer Block 
// using the anonymous object

class Sample {
  {
    System.out.println("Instance initializer block called");
  }

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

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

Output

Instance initializer block called
Constructor called

Explanation

In the above program, we created two classes Sample and Main. The Sample class contains an 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 an anonymous object of the Sample class and called IIB and constructor of the class.

Java Instance Initializer Block Programs »





Comments and Discussions!

Load comments ↻





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