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:
- Static blocks and static members are executed in the order they appear in the class
- Firstly the static blocks (and static members) in the parent class at the top of the hierarchy tree.
- Then the static blocks (and static members) in the subsequent class down to the current class.
- The super() and this() are called up to the Object class.
- Instance variables are given their values (including default values) in the parent class
- Instance blocks are executed in the parent in the order they appear in the class.
- Instance blocks can give value to instance variables;
- Instance blocks can use instance variables, if they are defined before the instance block in the code.
- See examples below.
- The code in the constructors that were called on the way up is executed.
- 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
Leave a Reply