標籤:成員變數 靜態方法 convert class space print server 變數 blog
1 public class Test { //1.第一步,準備載入類 2 3 public static void main(String[] args) { 4 new Test(); //4.第四步,new一個類,但在new之前要處理匿名代碼塊 5 } 6 7 static int num = 4; //2.第二步,靜態變數和靜態代碼塊的載入順序由編寫先後決定 8 9 {10 num += 3;11 System.out.println("b"); //5.第五步,按照順序載入匿名代碼塊,代碼塊中有列印12 }13 14 int a = 5; //6.第六步,按照順序載入變數15 16 { // 成員變數第三個17 System.out.println("c"); //7.第七步,按照順序列印c18 }19 20 Test() { // 類的建構函式,第四個載入21 System.out.println("d"); //8.第八步,最後載入建構函式,完成對象的建立22 }23 24 static { // 3.第三步,靜態塊,然後執行靜態代碼塊,因為有輸出,故列印a25 System.out.println("a");26 }27 28 static void run() // 靜態方法,調用的時候才載入// 注意看,e沒有載入29 {30 System.out.println("e");31 }32 }
輸出:abcd
一般順序:靜態塊(靜態變數)——>成員變數——>代碼塊——>構造方法——>靜態方法
1、靜態代碼塊(只載入一次) 2、構造方法(建立一個執行個體就載入一次)3、靜態方法需要調用才會執行,所以最後結果沒有e
1 public class Print {2 3 public Print(String s){4 System.out.print(s + " ");5 }6 }
1 public class Parent{ 2 3 public static Print obj1 = new Print("1"); 4 5 public Print obj2 = new Print("2"); 6 7 public static Print obj3 = new Print("3"); 8 9 static{10 new Print("4");11 }12 13 public static Print obj4 = new Print("5");14 15 public Print obj5 = new Print("6");16 17 public Parent(){18 new Print("7");19 }20 21 }
1 public class Child extends Parent{ 2 3 static{ 4 new Print("a"); 5 } 6 7 public static Print obj1 = new Print("b"); 8 9 public Print obj2 = new Print("c");10 11 public Child (){12 new Print("d");13 }14 15 public static Print obj3 = new Print("e");16 17 public Print obj4 = new Print("f");18 19 public static void main(String [] args){20 Parent obj1 = new Child ();21 Parent obj2 = new Child ();22 }23 }
執行main方法,程式輸出順序為: 1 3 4 5 a b e 2 6 7 c f d 2 6 7 c f d
輸出結果表明,程式的執行順序為:
如果類還沒有被載入:
1、先執行父類的靜態代碼塊和靜態變數初始化,並且靜態代碼塊和靜態變數的執行順序只跟代碼中出現的順序有關。
2、執行子類的靜態代碼塊和靜態變數初始化。
3、執行父類的執行個體變數初始化
4、執行父類的建構函式
5、執行子類的執行個體變數初始化
6、執行子類的建構函式
如果類已經被載入:
則靜態代碼塊和靜態變數就不用重複執行,再建立類對象時,只執行與執行個體相關的變數初始化和構造方法。
(轉)面試題--JAVA中靜態塊、靜態變數載入順序詳解