In java, we have three types of initializers:
1. Static Initializer:can be used to set the value of any static variables in a class. This is called when the class is loaded into JVM.
2. Instance Initializer:It is used to initialize the instance data members. It runs each time when object of the class is created.The Java compiler copies initializer blocks into every constructor.If the class extends any parent class, then the initializer block content will be copied after super() in the constructor.You can have multiple instance initializer blocks in a class in which case they execute in the sequence in which they appear in the class.
3. Constructor:It is used to initialize the instance data members. It runs each time when object of the class or object of the child class is created.
Let us look into the below example
Let us look into the contents of the TestInitializer.class file
When to use Instance Initializers
1. As Java compiler copies initializer blocks into every constructor.Therefore,instance initializers are invoked regardless of which constructor is used for Object creation.This approach can be used to share a block of code between multiple constructors.
2. Instance initializers are also useful in anonymous inner classes, which can’t declare any constructors at all.