Tuesday, 11 March 2014

Java static block

The static block in java is very similar to init block. The difference is instead of getting called before the constructor the static block gets called when the class is loaded in JVM. So when a instance of a class is created a static block gets called, then the init block and then the constructor. The static block's syntax is similar to init block with a difference that a term static needs to be places before the opening curly braces.
A class can have multiple static blocks and their execution will depend upon the order in which they are placed. Please note that just like static methods you can not initialize a instance variable in a static block.



Below example shows how static block works in inheritance.
Here when we create a instance of sub class, the static block of the super class is called and then the static block of the sub class. Then the constructor of the super class is called as there is not init blocks in super class. Then the init block of sub class and then the constructor of the sub class get called.

public class Animal {

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


public class Dog extends Animal{

 static
 {
  System.out.println("Dog static 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 static block
Dog static block1
Animal constructur called
Dog init block2
Dog constructur called


Share the post