ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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.

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 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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.