Monday 21 July 2014

Java initialization order

I was interested in what order java initialize objects in the class and its duper class. So, I wrote small program to get it:

 class Super {  
   static {  
     System.out.println("The first Super static init block");  
   }  
   static StaticSuperField staticSuperField = new StaticSuperField();  
   SuperField superField = new SuperField();  
   static {  
     System.out.println("The second Super static init block");  
   }  
   Super() {  
     System.out.println("The Super constructor");  
   }  
   {  
     System.out.println("The Super non-static init block");  
   }  
 }  
 public class Sub extends Super {  
   {  
     System.out.println("The Sub non-static init block");  
   }  
   static {  
     System.out.println("The first Sub static init block");  
   }  
   static StaticSubField staticSubField = new StaticSubField();  
   private SubField subField = new SubField();  
   static {  
     System.out.println("The second Sub static init block");  
   }  
   Sub() {  
     System.out.println("The Sub constructor");  
   }  
   public static void main(String[] args) {  
     new Sub();  
   }  
 }  
 class StaticSubField {  
   public StaticSubField() {  
     System.out.println("The static sub field");  
   }  
 }  
 class SubField {  
   public SubField() {  
     System.out.println("The sub field");  
   }  
 }  
 class StaticSuperField {  
   StaticSuperField() {  
     System.out.println("The static super field");  
   }  
 }  
 class SuperField {  
   SuperField() {  
     System.out.println("The super field");  
   }  
 }  

And got the output:

The first Super static init block
The static super field
The second Super static init block
The first Sub static init block
The static sub field
The second Sub static init block
The super field
The Super non-static init block
The Super constructor
The Sub non-static init block
The sub field
The Sub constructor

So, clear to see that the first class that is loaded to the JVM will be the super class of need Sub.
Also, you can see static members (not important which blocks or field) runs in the order that they appears in the code.
Obvious that the all fields initialized before a constructor finishes, and after the Super constructor runs.

Finally the initialization order of a class is:
  1. Static members (in the order they appeared in a class, not important if it is block or field).
  2. Non-static fields are given their default values
  3. Than the constructor starts and calls super();
  4. After super() is finished, non-static members are initialized, and here the same rule as for statics members(in the order they appeared in a class).
  5. And the last step, a constructor finishes.

No comments:

Post a Comment