Instance initializer block

Inside instance block we can perform some extra operations while initializing the instance variable. Of cause we can do initialization inside constructor also, but when we have multiple constructors (overloaded constructors) in our class, and we have certain common operations or initialization in each constructor then we can write those common operations in instance block. Like this way we can make sure that irrespective of any constructor invoked that common operations would be executed or taken care by JVM itself.

This instance block helps to avoid boiler plate code in overloaded constructor

There are mainly three rules for the instance initializer block. They are as follows

  1. The instance initializer block is created when instance of the class is created.
  2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
  3. The instance initializer block comes in the order in which they appear.

Code before compile

public class Demo {
 {
  System.out.println("Hello Instance block1");
 }
 {
  System.out.println("Hello Instance block2");
 }
 Demo(){
  System.out.println("Hello Constructor");
 }
 void display() {
  System.out.println("Hello Display");
 }
 public static void main(String[] args) {
  new Demo().display();
 }
}

Code After Compile(Class file)

public class Demo {
 Demo(){
  super();
  {
   System.out.println("Hello Instance block1");
  }
  {
   System.out.println("Hello Instance block2");
  }
  System.out.println("Hello Constructor");
 }
 void display() {
  System.out.println("Hello Display");
 }
 public static void main(String[] args) {
  new Demo().display();
 }
}

Instance initializer block is useful when there are multiple constructors overloaded in the same class, then we might have to repeat some set of codes in all constructor instead we can make use of initializer block which is automatically called in all the constrcutors.

public class Demo {
 {
  System.out.print("Hello Instance block ");
 }
 Demo(){
  System.out.print("Hello Constructor1 ");
 }
 Demo(String x){
  System.out.print("Hello Constructor2 ");  
 }
 void display() {
  System.out.println("Hello Display ");
 }
 public static void main(String[] args) {
  new Demo().display();
  new Demo("Hello Heapwizard").display();
 }
}

Leave a Comment