Pages

Saturday, May 05, 2012

Intialization Precedance in Java with Constructors, Intialization block, Static block

Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in the order they appear in the code. I've read that it's the same across classes, but some sample code I wrote disagrees with that. I used this code:

package pkg;
public class LoadTest {
   
public static void main(String[] args) {
       
System.out.println("START");
       
new Child();
       
System.out.println("END");
   
}
}
class Parent extends Grandparent {
   
// Instance init block
   
{
       
System.out.println("instance - parent");
   
}

   
// Constructor
   
public Parent() {
       
System.out.println("constructor - parent");
   
}

   
// Static init block
   
static {
       
System.out.println("static - parent");
   
}
}
class Grandparent {
   
// Static init block
   
static {
       
System.out.println("static - grandparent");
   
}

   
// Instance init block
   
{
       
System.out.println("instance - grandparent");
   
}

   
// Constructor
   
public Grandparent() {
       
System.out.println("constructor - grandparent");
   
}
}
class Child extends Parent {
   
// Constructor
   
public Child() {
       
System.out.println("constructor - child");
   
}

   
// Static init block
   
static {
       
System.out.println("static - child");
   
}

   
// Instance init block
   
{
       
System.out.println("instance - child");
   
}
}

The obvious answer from that is that parents' blocks run before their children's, but that could just be a coincidence and doesn't help if two classes aren't in the same hierarchy.

Output:

START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END


No comments:

Post a Comment