前些日至寫代碼的時候又碰到一個問題,類似于這樣:
image.png
子類調用父類的構造器,傳入自身的非靜態成員變量,編譯器會報錯
依稀記得以前整理過,所以又去寫了一遍相關的測試,代碼如下:
public class Child extends Parent{
static String flag = "Child:";
Msg msg = new Msg(flag+"field");
static Msg msgs = new Msg(flag+"static field");
static {
List<Msg> list = Arrays.asList(new Msg(flag+"static area"));
}
public Child(){
System.out.println(flag+"init");
}
}
public class Parent extends GrantParent{
static String flag = "Parent:";
Msg msg = new Msg(flag+"field");
static Msg msgs = new Msg(flag+"static field");
static {
List<Msg> list = Arrays.asList(new Msg(flag+"static area"));
}
public Parent(){
System.out.println(flag+"init");
}
}
public class GrantParent {
static String flag = "GrantParent:";
Msg msg = new Msg(flag+"field");
static Msg msgs = new Msg(flag+"static field");
static {
List<Msg> list = Arrays.asList(new Msg(flag+"static area"));
}
public GrantParent(){
System.out.println(flag+"init");
}
}
public class Msg {
public Msg(String str){
System.out.println(str);
}
}
@org.junit.Test
public void testInit(){
Child child = new Child();
}
輸出為:
image.png
由此可以總結出,java類初始化的順序為:
1.由基類到導出類的靜態成員變量和靜態代碼塊的初始化執行
2.1執行完后,再由基類到導出類的成員變量和構造器的初始化執行,同級的成員變量早于構造器被初始化