1. //: c08:BigEgg2.java
2. // Proper inheritance of an inner class.
3. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
4. // www.BruceEckel.com. See copyright notice in CopyRight.txt.
5. import com.bruceeckel.simpletest.*;
6.
7. class Egg2 {
8. protected class Yolk {
9. public Yolk() { System.out.println("Egg2.Yolk()"); }
10. public void f() { System.out.println("Egg2.Yolk.f()");}
11. }
12. private Yolk y = new Yolk();
13. public Egg2() { System.out.println("New Egg2()"); }
14. public void insertYolk(Yolk yy) { y = yy; }
15. public void g() { y.f(); }
16. }
17.
18. public class BigEgg2 extends Egg2 {
19. private static Test monitor = new Test();
20. public class Yolk extends Egg2.Yolk { //该类的内部类继承于基类的内部类
21. public Yolk() { System.out.println("BigEgg2.Yolk()"); }
22. public void f() {
23. System.out.println("BigEgg2.Yolk.f()");
24. }
25. }
26. public BigEgg2() { insertYolk(new Yolk()); } //1、实例化BigEgg2对象,在基类中找到insert方法2、然后实例化Yolk对象,其基类为Egg2中的内部类3、实例化13行的egg2对象4、在insert方法后将本类中的YOKL对象赋值给y,在调用g()的时候,返回本内部类中的f()方法
27. public static void main(String[] args) {
28. Egg2 e2 = new BigEgg2();
29. e2.g();
30. monitor.expect(new String[] {
31. "Egg2.Yolk()",
32. "New Egg2()",
33. "Egg2.Yolk()",
34. "BigEgg2.Yolk()",
35. "BigEgg2.Yolk.f()"
36. });
37. }
38. } ///:~