前些日至写代码的时候又碰到一个问题,类似于这样:
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执行完后,再由基类到导出类的成员变量和构造器的初始化执行,同级的成员变量早于构造器被初始化
网友评论