功能概述
- 在創(chuàng)建Java對象時(shí),需要將對象中的成員變量進(jìn)行初始化后,才能調(diào)用對象的構(gòu)造方法創(chuàng)建對象。本文中將會(huì)講解初始化時(shí)父類與子類對應(yīng)的順序。
功能實(shí)踐
場景1:父類、子類的初始化順序
用例代碼
@Test
public void test_init_order() {
new Child();
}
public class Parent {
static {
System.out.println("父類靜態(tài)塊");
}
{
System.out.println("父類非靜態(tài)塊");
}
public Parent() {
System.out.println("父類構(gòu)造方法");
}
}
public class Child extends Parent {
static {
System.out.println("子類靜態(tài)塊");
}
{
System.out.println("子類非靜態(tài)塊");
}
public Child() {
System.out.println("子類構(gòu)造方法");
}
}
結(jié)果輸出
父類靜態(tài)塊
子類靜態(tài)塊
父類非靜態(tài)塊
父類構(gòu)造方法
子類非靜態(tài)塊
子類構(gòu)造方法
結(jié)果分析
- 先初始化靜態(tài)塊:父類的靜態(tài)塊 -> 子類的靜態(tài)塊。
- 再初始化非靜態(tài)塊以及構(gòu)造方法:
- 父類的非靜態(tài)塊 -> 父類的構(gòu)造方法
- 子類的非靜態(tài)塊 -> 子類的構(gòu)造方法
場景2:塊、成員域中初始化順序
用例代碼
static {a = 2;} //靜態(tài)塊中初始化
static int a = 1; //成員域中初始化
static int b = 3;
static {b = 4;}
{c = 5;} //可以放在聲明的上面
int c = 3;
@Test
public void test_order() {
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
結(jié)果輸出
1
4
3
結(jié)果分析
- 塊中的初始化與成員域中的初始化是平級的,所以會(huì)按照從上到下初始化,最后一次初始化為最終的值。
場景3:靜態(tài)變量的調(diào)用
用例代碼
@Test
public void test_static_var() {
System.out.println(InitB.c);
}
public class InitA {
public static String c = "C";
static {
System.out.println("A");
}
}
public class InitB extends InitA {
static {
System.out.println("B");
}
}
用例輸出
A
C
結(jié)果分析
- 因?yàn)檎{(diào)用InitB.c,static變量c在A類中,所以會(huì)加載父類A,所以輸出了靜態(tài)塊中的"A"。
- 因?yàn)镮nitB.c直接訪問InitA的變量,不需要訪問InitB中的其它內(nèi)容,所以就不要加載InitB了。
功能總結(jié)
- 初始化時(shí),執(zhí)行的順序?yàn)椋焊割愳o態(tài)變量 -> 父類靜態(tài)代碼塊 -> 子類靜態(tài)變量 -> 子類靜態(tài)代碼塊 -> 父類非靜態(tài)變量 -> 父類非靜態(tài)代碼塊 -> 父類構(gòu)造方法 -> 子類非靜態(tài)變量 -> 子類的非靜態(tài)代碼塊 -> 子類構(gòu)造方法。
文章來源地址http://www.zghlxwxcb.cn/news/detail-682324.html
文章來源:http://www.zghlxwxcb.cn/news/detail-682324.html
到了這里,關(guān)于Java之初始化順序?qū)嵺`的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!