關(guān)于類和實(shí)例變量初始化過(guò)程移稳,我們直接看代碼來(lái)解釋比較好理解犀勒。
代碼如下:
public class Father{
private int i = test();
private static int j = method();
static{
System.out.print("(1)");
}
Father(){
System.out.print("(2)");
}
{
System.out.print("(3)");
}
public int test(){
System.out.print("(4)");
return 1;
}
public static int method(){
System.out.print("(5)");
return 1;
}
}
public class Son extends Father{
private int i = test();
private static int j = method();
static{
System.out.print("(6)");
}
Son(){
// super();//寫或不寫都在屎飘,在子類構(gòu)造器中一定會(huì)調(diào)用父類的構(gòu)造器
System.out.print("(7)");
}
{
System.out.print("(8)");
}
public int test(){
System.out.print("(9)");
return 1;
}
public static int method(){
System.out.print("(10)");
return 1;
}
public static void main(String[] args) {
Son s1 = new Son();
System.out.println();
Son s2 = new Son();
}
}
執(zhí)行結(jié)果如下:
(5)(1)(10)(6)(9)(3)(2)(9)(8)(7)
(9)(3)(2)(9)(8)(7)
我們根據(jù)程序執(zhí)行結(jié)果來(lái)分析可以得知:
類和實(shí)例變量的初始化過(guò)程:
程序首先初始化父類,再初始化子類贾费。
具體初始化順序如下:
第一步首先初始化類
1)靜態(tài)實(shí)例變量
2)靜態(tài)代碼塊
3)它倆誰(shuí)在程序前邊誰(shuí)先執(zhí)行
第二步初始化類的實(shí)例變量
1)初始化非靜態(tài)變量
2)非靜態(tài)代碼塊
3)它倆誰(shuí)在程序前邊誰(shuí)先執(zhí)行
4)父構(gòu)造器
5)子構(gòu)造器
需要注意的是程序中的test()方法為重寫的方法钦购,Son對(duì)象在初始化時(shí)執(zhí)行的是Son類里的test()方法。
非靜態(tài)方法前面其實(shí)有一個(gè)默認(rèn)的對(duì)象this褂萧,this在構(gòu)造器(或<init>)它表示的是正在創(chuàng)建的對(duì)象押桃,因?yàn)檫@里是在創(chuàng)建Son對(duì)象,所以test()執(zhí)行的是子類重寫的代碼(面向?qū)ο蠖鄳B(tài))箱玷。