Static Initialization Block
- The static initialization block is executed only once when a class is loaded the first time.
- Multiple static initialization block is allowed.
Instance Initialization Block
- The instance initialization block is executed whenever a new instance is created.
- Multiple instance initialization block is allowed.
Order of executions
- The static initialization block is executed first.
- Instance initialization block is executed after all super constructor is executed and before the execution constructor of their own class.
- If we have multiple blocks in the same class then they will execute in the sequence it has been declared but first all static blocks and then all instance blocks.
Example
Class Animal
Class Dog subclass of Animal
Now we will create an instance of the Dog class in TestOrder and verify the order of execution of the constructor and blocks
Output
1st dog static block called
2nd dog static block called
Animal constructor called.
1st dog instance block called
2nd dog instance block called
Dog constructor called
Another post you may like to refer
For spring tutorial visit Spring Tutorial
Thanks
Happy Learning!
0 Comments
If you have any doubts let me know.