class Meal {
Meal() {
System.out.println("Meal()"); // 5
}
}
class Lunch extends Meal {
private static Demo4 demo4 = new Demo4(); //1
private Demo demo = new Demo(); // 6
static {
System.out.println("lunch static code ");//2
}
Lunch() {
System.out.println("Lunch()"); //7
}
}
public class Sandwich extends Lunch {
private static Demo3 demo3 = new Demo3();//3
private Demo2 demo2 = new Demo2(); // 8
static{
System.out.println("Sandwich static code");//4
}
Sandwich() {
System.out.println("Sandwich()"); // 9
}
public static void main(String[] args) {
Sandwich sandwich = new Sandwich();
}
}
class Demo {
Demo() {
System.out.println("Demo()");
}
}
class Demo2 {
Demo2() {
System.out.println("Demo2()");
}
}
class Demo3 {
Demo3() {
System.out.println("Demo3()");
}
}
class Demo4 {
Demo4() {
System.out.println("Demo4()");
}
}
观察上面的执行顺序,可得:
- 首先调用基类的静态成员变量的初始化方法,调用基类的静态代码块,逐层这样调用,直到最低层
- 调用基类的成员变量初始化方法,调用基类的构造函数,逐层这样调用,直到最低层
网友评论