Instance Initialization Block (IIB) in Java
In a Java program, operations can be performed on methods, constructors, and initialization blocks. Instance Initialization Blocks or IIBs are used to initialize instance variables. So firstly, the constructor is invoked and the java compiler copies the instance initializer block in the constructor after the first statement super(). They run each time when the object of the class is created.
- Initialization blocks are executed whenever the class is initialized and before constructors are invoked.
- They are typically placed above the constructors within braces.
- It is not at all necessary to include them in your classes.
IIB block Constructor Called
Multiple Instance Initialization Blocks in a Program
We can also have multiple IIBs in a single class. If the compiler finds multiple IIBs, then they all are executed from top to bottom i.e. the IIB which is written at the top will be executed first.
IIB1 block IIB2 block IIB3 block Constructor Called
Instance Initialization Block with parent class
You can have IIBs in parent class also. Instance initialization block code runs immediately after the call to super() in a constructor. The compiler executes the parent’s class’s IIB before executing the current class’s IIBs.
Have a look at the following example.
B-IIB block B-Constructor Called A-IIB block A-Constructor Called
In the above example, the compiler tries to execute the class A constructor, when the object of class A is created. But it finds super() statement and goes to the parent class constructor first to be executed. The order of execution, in this case, will be as follows:
- Instance Initialization Block of the superclass.
- Constructors of the superclass.
- Instance Initialization Blocks of the subclass.
- Constructors of the subclass.
- Instance Initialization Blocks run every time a new instance is created.
- Initialization Blocks run in the order they appear in the program
- The Instance Initialization Block is invoked after the parent class constructor is invoked (i.e. after super() constructor call)
Related Article :
The Initializer Block in Java
This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.