java 内部类可以被覆盖吗
如果创建了一个内部类,然后继承其外围类并重新定义内部类时,"覆盖"内部类就好像是其外围类的一个方法,并不起作用,
这两个内部类是完全独立的两个实体,各自在自己的命名空间内
//: innerclasses/BigEgg.java // An inner class cannot be overriden like a method. import static net.mindview.util.Print.*; class Egg { private Yolk y; protected class Yolk { public Yolk() { print("Egg.Yolk()"); } } public Egg() { print("New Egg()"); y = new Yolk(); } } public class BigEgg extends Egg { public class Yolk { public Yolk() { print("BigEgg.Yolk()"); } //这里并没有输出 } public static void main(String[] args) { new BigEgg(); } } /* Output: New Egg() Egg.Yolk() *///:~
当然,明确的继承某个内部类也是可以的
//: innerclasses/BigEgg2.java // Proper inheritance of an inner class. import static net.util.Print.*; class Egg2 { protected class Yolk { public Yolk() { print("Egg2.Yolk()"); } public void f() { print("Egg2.Yolk.f()");} } private Yolk y = new Yolk(); public Egg2() { print("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 { //通过继承明确的继承了Egg2.Yolk类,并覆盖了其中的方法 public Yolk() { print("BigEgg2.Yolk()"); } public void f() { print("BigEgg2.Yolk.f()"); } } public BigEgg2() { insertYolk(new Yolk()); }//向上转型成Egg2.Yolk类 public static void main(String[] args) { Egg2 e2 = new BigEgg2(); e2.g(); } } /* Output: Egg2.Yolk() New Egg2() Egg2.Yolk() BigEgg2.Yolk() BigEgg2.Yolk.f() *///:~