麻煩先看代碼主要內(nèi)容是關(guān)于靜態(tài)初始化和構(gòu)造器的執(zhí)行順序的問題class Root{ static { System.out.println("Root的靜態(tài)初始化代碼塊"); } { System.out.println("Root的普通初始化代碼塊"); } public Root() { System.out.println("Root的無參數(shù)的構(gòu)造器"); }}class Mid extends Root{ static { System.out.println("Mid的靜態(tài)初始化代碼塊"); } { System.out.println("Mid的普通初始化代碼塊"); } public Mid() { System.out.println("Mid的無參數(shù)構(gòu)造器"); } public Mid(String msg) { //通過this調(diào)用同一類中的重載構(gòu)造器 //this(); System.out.println("Mid的帶參數(shù)構(gòu)造器,其參數(shù)值為:" + msg ); }}class Leaf extends Mid{ static { System.out.println("Leaf的靜態(tài)初始化代碼塊"); } { System.out.println("Leaf的普通初始化代碼塊"); } public Leaf() { //通過super調(diào)用父類中有一個(gè)字符串參數(shù)的構(gòu)造器 super("急速測試"); System.out.println("執(zhí)行Leaf的構(gòu)造器"); }}public class Test { public static void main(String [] args) { System.out.println("test"); new Leaf(); new Leaf(); }}代碼輸出如下testRoot的靜態(tài)初始化代碼塊Mid的靜態(tài)初始化代碼塊Leaf的靜態(tài)初始化代碼塊Root的普通初始化代碼塊Root的無參數(shù)的構(gòu)造器Mid的普通初始化代碼塊Mid的帶參數(shù)構(gòu)造器,其參數(shù)值為:急速測試Leaf的普通初始化代碼塊執(zhí)行Leaf的構(gòu)造器Root的普通初始化代碼塊Root的無參數(shù)的構(gòu)造器Mid的普通初始化代碼塊Mid的帶參數(shù)構(gòu)造器,其參數(shù)值為:急速測試Leaf的普通初始化代碼塊執(zhí)行Leaf的構(gòu)造器問題1(此問題已經(jīng)解決,謝謝)我粗略了解載入Leaf類的時(shí)候,會(huì)先創(chuàng)建父類(直至java.lang.Object)的初始化代碼和構(gòu)造器,那么他們的順序是否如下:Root類靜態(tài)初始化代碼塊-->Mid類靜態(tài)初始化代碼塊-->Leaf類靜態(tài)初始化代碼塊-->Root類普通初始化代碼塊-->Root類構(gòu)造器-->...-->Leaf類Root類普通初始化代碼塊-->Leaf類的構(gòu)造器問題2如果Leaf類的構(gòu)造器的執(zhí)行順序在父類的構(gòu)造器之后,那么為什么Mid類的有參數(shù)構(gòu)造器已經(jīng)被傳入?yún)?shù)急速測試呢?可能描述得不是很清楚,如果有疑問請指出來,我會(huì)盡量描述清楚的感謝您抽空查看
添加回答
舉報(bào)
0/150
提交
取消