類的加載和初始化的了解對于我們對編程的理解有很大幫助,最近在看類的記載方面的問題。從網上查閱了若干文章,現總結如下:
單獨一個類的場景下,初始化順序為依次為 靜態數據,繼承的基類的構造函數,成員變量,被調用的構造函數。
其中靜態數據只會初始化一次。
public class App2 { public static void main(String[] args) { Son son = new Son(); }}class Son { public Son() { System.out.PRintln("this is son."); } public Son(int age) { System.out.println("son is " + age + " years old."); } private Height height = new Height(1.8f); public static Gender gender = new Gender(true);}class Height { public Height(float height) { System.out.println("initializing height " + height + " meters."); }}class Gender { public Gender(boolean isMale) { if (isMale) { System.out.println("this is a male."); } else { System.out.println("this is a female."); } }}輸出:
2. 繼承的情況
稍微修改一下代碼,添加兩個基類,讓Son繼承Father, Father繼承Grandpa。
繼承的情況就比較復雜了。由于繼承了基類,還將往上回溯,遞歸地調用基類的無參構造方法。
在我們的例子中,在初始化靜態數據后,會先往上追溯,調用Father的默認構造方法,此時再往上追溯到Grandpa的默認構造方法。
注:如果在子類的構造方法中,顯式地調用了父類的帶參構造方法,那么JVM將調用指定的構造方法而非默認構造方法。
我們繼續修改代碼,讓其最終呈現如下:public class App2 { public static void main(String[] args) { Son son = new Son(); }}class Grandpa { public Grandpa() { System.out.println("this is grandpa."); } public Grandpa(int age) { System.out.println("grandpa is " + age + " years old."); } private Height height = new Height(1.5f); public static Gender gender = new Gender(true, "grandpa");}class Father extends Grandpa { public Father() { System.out.println("this is father."); } public Father(int age) { System.out.println("father is " + age + " years old."); } private Height height = new Height(1.6f); public static Gender gender = new Gender(true, "father");}class Son extends Father { public Son() { super(50); System.out.println("this is son."); } public Son(int age) { System.out.println("son is " + age + " years old."); } private Height height = new Height(1.8f); public static Gender gender = new Gender(true, "son");}class Height { public Height(float height) { System.out.println("initializing height " + height + " meters."); }}class Gender { public Gender(boolean isMale) { if (isMale) { System.out.println("this is a male."); } else { System.out.println("this is a female."); } } public Gender(boolean isMale, String identify) { if (isMale) { System.out.println(identify + " is a male."); } else { System.out.println(identify + " is a female."); } }}最后輸出會是什么呢?
參考下面另一個案例的分析。鏈接:http://bbs.csdn.net/topics/310164953
在我們的示例中,加載順序應該是這樣的:
Grandpa 靜態數據
Father 靜態數據
Son 靜態數據
Grandpa 成員變量
Grandpa 構造方法
Father 成員變量
Father 構造方法
Son 成員變量
Son 構造方法
所以輸出如下:
新聞熱點
疑難解答