標籤:todo rate void ini log public string method pre
先看程式:
1 package init_cls; 2 3 class A{ 4 5 {System.out.println("i am in the class A!");} 6 static { System.out.println("static is the class A");} 7 } 8 public class init_cls { 9 {System.out.println("i am in the init_cls");}10 static{System.out.println("i am static in the init_cls class");}11 public static void main(String[] args) {12 // TODO Auto-generated method stub13 14 A a=new A();15 init_cls c=new init_cls();16 }17 18 }
運行結果為:
i am static in the init_cls class
static is the class A
i am in the class A!
i am in the init_cls
從結果中可以看到,當我們只是使用一個類中的方法的時候(在這裡使用的init_cls中的main),只初始化靜態變數,所以最先輸出:i am static in the init_cls class
之後當執行個體化一個類A的時候,先初始化其中的靜態域static ,所以輸出:static is the class A
之後初始化非靜態域,所以輸出:i am in the class A!
最後,只有當我們執行個體化init_cls類的時候,才初始化了類A中的非靜態域,有了輸出:i am in the init_cls
這些和python中的初始化順序非常不同,在python中載入一個包的時候,會從上到下全部初始化,遇到語句時候全部執行
[java] java中的初始化順序