public class House {
public House(String name){
System.out.println(name+" 's house");
}
}
public class GrandFather{
protected GrandFather(){
System.out.println("GrandFather()");
}
static{
System.out.println("static block in GrandFather");
}
{
System.out.println("initialization in GrandFather");
}
static House h1 = new House("static GrandFather");
House h2 = new House("GrandFather");
}
public class Father extends GrandFather{
static {
System.out.println("static block in Father");
}
static House h1 = new House("static Father");
protected Father(){
System.out.println("Father()");
}
{
System.out.println("initialization in Father");
}
}
public class son extends Father{
son() {
System.out.println("son()");
}
public static void main(String[] args) {
System.out.println("********entry in main********");
new son();
}
static House h1 = new House("static son");
static{
System.out.println("static block in son");
}
House h2 = new House("son");
{
System.out.println("block in son");
}
}
运行结果:
static block in GrandFather
static GrandFather 's house
static block in Father
static Father 's house
static son 's house
static block in son
********entry in main********
initialization in GrandFather
GrandFather 's house
GrandFather()
initialization in Father
Father()
son 's house
block in son
son()
结论:
在继承关系中,类成员的初始化遵照以下顺序
①最外层超类的静态成员
②超类静态成员
③子类静态成员
④最外层超类的非静态成员
⑤最外层超类的构造器
⑥超类的非静态成员
⑦超类的构造器
⑧子类的非静态成员
⑨子类构造器
其中,相同类型(同为静态或者非静态成员)复数成员的初始化,遵照其在代码中出现的顺序。
联系客服