ADVERTISEMENT
ADVERTISEMENT

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

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.

Program/Source Code:

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 »


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.