http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
Initialization blocks are places whereyou can perform operations like initialization of variables or execution of some statements. There are two kinds of initialization blocks
- static initialization blocks
- instance initialization blocks.
As their names suggest,
- static initialization blocks are static and hence they belong to a particular class and not to the instances of class. They are defined as static { //some statements here }
- Instance initialization blocks do not belong to a class and they are executed every time a new instance of the class is created. They are defined as {//some statements here}
There are certain rules regarding order of execution of initialization blocks and constructor. Let us list them down first and verify by writing a simple program.
- Initialization blocks run in the order they appear in the program.
- Static initialization blocks run when the class is first loaded into JVM
- Instance initialization blocks run whenever a new instance of class is created.
- Instance initialization blocks run AFTER the super constructor has completed executing and BEFORE current class constructor.
- They can be used to perform operations those are common to constructors