Q:

Java program to implement instance initializer block with superclass

0

Java program to implement instance initializer block with superclass

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/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 AB, 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to implement static block with instan... >>
<< Java program to initialize instance data member us...