关于继承内部类——java编程思想示例程序分析;
class Egg2 {
protected class Yolk {
public Yolk() {
System.out.println("Egg2.Yolk()");
}
public void f() {
System.out.println("Egg2.Yolk.f()");
}
}
private Yolk y = new Yolk();
public Egg2() {
System.out.println("New Egg2()");
}
public void insertYolk(Yolk yy) {
y = yy;
}
public void g() {
y.f();
}
}
public class BigEgg2 extends Egg2 {
public class Yolk extends Egg2.Yolk {
public Yolk() {
System.out.println("BigEgg2.Yolk()");
}
public void f() {
System.out.println("BigEgg2.Yolk.f()");
}
}
public BigEgg2() {
insertYolk(new Yolk());
}
public static void main(String[] args) {
Egg2 e2 = new BigEgg2();
e2.g();
}
}
程序运行结果:
Egg2.Yolk()
New Egg2()
Egg2.Yolk()
BigEgg2.Yolk()
BigEgg2.Yolk.f()
运行顺序:
1、Egg2 e2 = new BigEgg2();子类在实例化之前,先调用父类构造方法,父类构造方法先初始化类成员;
有 private Yolk y = new Yolk();,y作为Egg2类的成员先被初始化;先调用Egg2内部类yolk的构造函数;打印出Egg2.Yolk();
2、调用Egg2的构造函数;打印出Egg2.Yolk();
3、调用BigEgg2的构造函数;因为它insertYolk(new Yolk());这里的new Yolk是BigEgg2的内部类的实例;这个内部类继承了Egg2中的内部类
;所以先调用了Egg2中Yolk的构造函数;打印出Egg2.Yolk();
4、调用BigEgg2.Yolk的构造函数;打印出BigEgg2.Yolk();
5、e2.g();打印出BigEgg2.Yolk();
我不知道分析的对不对,如果不对,请指教zhaoqb@neusoft.com或者zqb@hanhuasoft.com