News Ticker

Initialisation Blocks and Constructors

The order of execution of static and non-static initialisation blocks and constructors can get a little confusing at times so here I present an ordered list of execution of initialisation blocks and constructors.

The order of execution:

  1. Static blocks and static members are executed in the order they appear in the class
    1. Firstly the static blocks (and static members) in the parent class at the top of the hierarchy tree.
    2. Then the static blocks (and static members) in the subsequent class down to the current class.
  2. The super() and this() are called up to the Object class.
  3. Instance variables are given their values (including default values) in the parent class
  4. Instance blocks are executed in the parent in the order they appear in the class.
    1. Instance blocks can give value to instance variables;
    2. Instance blocks can use instance variables, if they are defined before the instance block in the code.
    3. See examples below.
  5. The code in the constructors that were called on the way up is executed.
  6. From the parent class down to the current class.

Time for an example:


ParentStatics.class

[sourcecode language=”java” toolbar=”false”]
public class ParentStatics {

static String s1 = sM2("parent static member"); // 1

{s1 = sM2("parent init block"); } // 5

static{s1 = sM2("parent static init"); } // 2

private static String sM2(String s){
System.out.println(s);
return s;
}
}
[/sourcecode]

Statics.class

[sourcecode language=”java” toolbar=”false”]
public class Statics extends ParentStatics{

static String s1 = sM1("child static member"); // 3

{s1 = sM1("child init block"); } // 6

static{s1 = sM1("child static block"); } // 4

public static void main(String args[]){
Statics it = new Statics();
}

private static String sM1(String s){
System.out.println(s);
return s;
}
}
[/sourcecode]

The output will be:


1. parent static member
2. parent static init
3. child static member
4. child static block
5. parent init block
6. child init block

1 Trackback / Pingback

  1. Welcome « alex.theedom

Leave a Reply