Tuesday, 11 March 2014

Java init block

Init block is a code of block that gets executed before the constructor of a class gets called. It is denoted by open and closed curly braces without any name.
Their could be multiple init blocks inside a class. Their execution depends upon the order in which they are written. Init block are generally used when a common code needs to be invoked for every constructor, so instead of writing the same code in every constructor we can write the code in a common init block. below examples shows when and how init block gets called in inheritance.



In case of inheritance first the if we create a instance of a sub class then before calling the constructor of super class all init blocks of super class are called, then the super constructor is called. After that before the sub class constructor gets called, all the init blocks of the sub class gets called.

public class Animal {

 {
  System.out.println("Animal init block");
 }
 public  Animal(){
  System.out.println("Animal constructur called");
 }
}


public class Dog extends Animal{

 {
  System.out.println("Dog init block1");
 }
 {
  System.out.println("Dog init block2");
 }
 public Dog(){
  System.out.println("Dog constructur called");
 }
 
}
public class Test {

 public static void main(String[] args) {
  Dog dog = new Dog();
 }
}

Animal init block
Animal constructur called
Dog init block1
Dog init block2
Dog constructur called


For static block refer Static block

Share the post