public class Person{{a = 6;//if (a > 4){System.out.println("Person init block a > 4");}}public int a = 9;{System.out.println("second executed");}static {//即使不執行個體化對象也會執行System.out.println("Person static block");}public static void main(String[] args){//Person p = new Person();//System.out.println(" a " + p.a);Leaf l = new Leaf();Leaf ll = new Leaf();}}class Root{static{System.out.println("root static init");}{System.out.println("root normal init");}public Root(){System.out.println("root constructor");}}class Mid extends Root{static{System.out.println("mid static init");}{System.out.println("mid normal init");}public Mid(){System.out.println("mid constructor");}}class Leaf extends Mid{static{System.out.println("Leaf static init");}{System.out.println("Leaf normal init");}public Leaf(){System.out.println("Leaf constructor");}}
輸出結果為:
Person static block
root static init
mid static init
Leaf static init
root normal init
root constructor
mid normal init
mid constructor
Leaf normal init
Leaf constructor
root normal init
root constructor
mid normal init
mid constructor
Leaf normal init
Leaf constructor
初始化 順序 :
靜態 初始化塊(父類 ---> 子類 )---->父類 的 非靜態初始化塊(聲明屬性執行個體預設值 (由初始化塊和預設值定義聲明的順序決定執行順序 )) -----> 父類的建構函式 -------> 子類的非靜態初始化塊 (聲明屬性執行個體預設值 (由初始化塊和預設值定義聲明的順序決定執行順序 )) ---------> 子類的建構函式