Think in Java P269
如果子类中的内部类和父类中内部类一样,这好像子类内部类“覆盖”了父类的内部类,但其实没有代表着什么。
public class BigEgg extends Egg { public class Yolk { public Yolk() { System.out.println("BigEgg.Yolk()"); } } public static void main(String[] args) { new BigEgg(); } } class Egg { private Yolk y; protected class Yolk { public Yolk() { System.out.println("Egg.yolk( )"); } } public Egg() { System.out.println("New Egg()"); y = new Yolk(); } }
输出结果:
New Egg()
Egg.yolk( )
结果表明 内部类在继承中并没有表现其他的特性 ,两个是两个完全独立的实体。
class Egg2 { protected class Yolk { public Yolk() { print("Egg2.Yolk()"); } public void f() { print("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 void print(String msg) { System.out.println(msg); } } public class BigEgg2 extends Egg2 { public class Yolk extends Egg2.Yolk { public Yolk() { print("BigEgg2.Yolk()"); } public void f() { print("BigEgg2.Yolk.f()"); } } public BigEgg2() { insertYolk(new Yolk()); } public static void main(String[] args) { Egg2 e2 = new BigEgg2(); e2.g(); } public void print(String msg) { System.out.println(msg); } }
输出:
Egg2.Yolk()
new Egg2
Egg2.Yolk()
BigEgg2.Yolk()
BigEgg2.Yolk.f()
1.父类变量初始化
private Yolk y = new Yolk();
此时调用的是父类的Yolk,所以输出的结果是Egg2.Yolk()
2.父类构造函数,输出 new Egg2
3.子类构造函数
insertYolk(new Yolk());
此时使用的是子类的Yolk,实例化子类,需要先实例化父类,所以 输出的结果是
Egg2.Yolk()
BigEgg2.Yolk()
4.代码 e2.g();
此时父类中的Yolk实际上是子类的Yolk,所以输出的结果是BigEgg2.Yolk.f()