Instance initializer block in Java
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
There are two types of initialization blocks:
- Static Initialization Blocks: Runs first when the class is first loaded. Declared by using the keyword "Static"
- Instance Initialization Blocks: Runs every time when the instance of the class is created.
Rule of Instance Initializer Block are:-
- Instance Initializer Block doesn't have any name.
- Instance Initializer Block can't take any argument.
- Instance Initializer Block doesn't return anything.
- We can have many Instance Initializer Blocks in a class.
- Instance Initializer Blocks run every time when a class instance is created.
- Instance Initializer Blocks execute inside the constructor of that class and after the call to all super class constructor.
- Instance Initializer Block code runs right after the call to super() in a constructor, in other words, after all super constructors have run.
- Unlike methods or constructors, Instance Initializer Block gets executed in the order, in which initialization blocks appear in a class.