×

Java Programs

Java Practice

Java program to implement instance initializer block with superclass

Learn how to implement instance initializer block with superclass in Java?
Submitted by Nidhi, on March 26, 2022

Problem statement

In this program, we will create a class with instance initializer block and constructor. Then we will inherit the created class into another class. Here, Super and Subclasses contain Instance Initializer Block.

Source Code

The source code to implement instance initializer block with superclass is given below. The given program is compiled and executed successfully.

// Java program to implement instance initializer block 
// with superclass

class A {
  // Instance Initializer Block
  {
    System.out.println("A: IIB Called");
  }

  A() {
    System.out.println("A: Constructor Called");
  }
}

class B extends A {
  // Instance Initializer Block
  {
    System.out.println("B: IIB Called");
  }

  B() {
    super();
    System.out.println("B: Constructor Called");
  }
}

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

Output

A: IIB Called
A: Constructor Called
B: IIB Called
B: Constructor Called

Explanation

In the above program, we created three classes A, B, and Main. Class A contains an Instance Initializer Block, a constructor. Then we inherited the class A into B. The A and B, Both class contains IIBs.

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 B class, it calls B class IIB and constructor, and B class constructor calls A class IIB and constructor.

Java Instance Initializer Block Programs »





Comments and Discussions!

Load comments ↻





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