深入瞭解類載入過程及Java程式執行順序
摘要:/**
* @author chris
* @date 2018/10/30 - 15:24
* 類載入執行順序:
* 1.靜態屬性,靜態方法宣告,靜態塊。
*
* 2.動態屬性,普通方法宣告,構造塊。
*
* 3.構造方法。
*
* 當new一個物件時,此時會呼叫構造方法,但是...
/** * @author chris * @date 2018/10/30 - 15:24 * 類載入執行順序: * 1.靜態屬性,靜態方法宣告,靜態塊。 * * 2.動態屬性,普通方法宣告,構造塊。 * * 3.構造方法。 * * 當new一個物件時,此時會呼叫構造方法,但是在呼叫構造方法之前,(除非被打斷而暫停)執行動態屬性定義並設定預設值(一舉生成的)。 */ public class Text { //類載入jvm先對屬性賦預設值 根據資料型別 public static int k = 0; // 1.靜態屬性 public static Text t1 = new Text("t1");//2.靜態屬性 new物件暫停了類載入過程去執行構造方法,但在之前先執行動態屬性定義並設定預設值 , // 然後動態屬性初始化,分配記憶體,構造塊,普通方法宣告(只是載入,它不需要初始化,只有呼叫它時才分配記憶體, // 當方法執行完畢後記憶體立即釋放),沒有優先順序之分,按出現順序執行。 public static Text t2 = new Text("t2");//重複上述操作 public static int i = print("i"); //靜態屬性 public static int n = 99; //靜態屬性至此靜態方法執行完畢開始執行靜態塊 public int j = print("j"); { print("構造塊");//構造塊 } static { print("靜態塊");//靜態塊 靜態塊執行完之後 執行main方法(main方法也屬於特殊靜態方法) } public Text(String str) { System.out.println((++k) + ":" + str + "i=" + i + "n=" + n); ++i; ++n; } public static int print(String str) { System.out.println((++k) + ":" + str + "i=" + i + "n=" + n); ++n; return ++i; } public static void main(String args[]) { Text t = new Text("init");//main方法開始之後開始執行動態屬性及程式碼塊 } } Text類載入執行是 最先jvm給屬性預設值(按資料型別)載入靜態屬性其中第二個靜態屬性被例項化過程打斷轉而在執行構造方法之前載入了動態屬性和構造塊 靜態屬性載入完成之後載入靜態塊 然後找到了靜態main方法開始例項化重複了之前兩個靜態屬性後的操作