面對物件——繼承中程式碼執行的順序問題
阿新 • • 發佈:2018-12-16
1、類中成員變數的初始化過程
預設初始化(賦值為預設值)——>顯式初始化(通過成員變數初始化)——>構造方法初始化(通過構造方法初始化)
2、子類和父類的初始化(分層初始化)
先初始化父類,然後初始化子類
3、程式碼中的程式碼塊執行順序
靜態程式碼塊(在載入類時執行,僅執行一次)——>構造方法程式碼塊(在建立物件時執行)——>構造方法
注意事項:
super()在程式碼中的意思是首先需要父類初始化,應該按照分層初始化的順序執行,並不是按照其程式碼順序執行。
class Father{ static { System.out.println("我是father靜態程式碼塊"); } { System.out.println("我是father構造方法程式碼塊"); } public Father(){ Mother mother = new Mother(); System.out.println("我是father構造方法"); } } class Mother { public Mother() { System.out.println("我是mother構造方法"); } } public class Son extends Father{ static { System.out.println("我是son靜態程式碼塊"); } Mother mother = new Mother(); public Son() { super(); System.out.println("我是son構造方法"); } public static void main(String [] args) { new Son(); } }
執行過程:
1、從main方法開始執行
2、載入father類,執行父類靜態程式碼塊 , 輸出“我是father靜態程式碼塊”
3、載入son類,執行子類靜態程式碼塊,輸出“我是son靜態程式碼塊”
4、初始化父類,執行父類構造方法程式碼塊,輸出“我是father構造方法程式碼塊”
5、父類構造方法初始化,建立mother物件,對mother初始化,輸出“我是mother構造方法”,然後輸出“我是father構造方法”
6、顯式初始化子類,建立mother物件,對mother初始化,輸出“我是mother構造方法”
7、構造方法初始化子類,輸出“我是son構造方法”
執行結果:
我是father靜態程式碼塊
我是son靜態程式碼塊
我是father構造方法程式碼塊
我是mother構造方法
我是father構造方法
我是mother構造方法
我是son構造方法