内部类可以实现多重继承类(类为抽象类或具体的类)
class D {} abstract class E {} class Z extends D { E makeE() { return new E() {}; } } public class MultiImplementation { static void takesD(D d) {} static void takesE(E e) {} public static void main(String[] args) { Z z = new Z(); takesD(z); takesE(z.makeE()); } } ///:~
内部类的继承
class WithInner { WithInner(){ System.out.println("WithInner!"); } class Inner { Inner(){ System.out.println("Inner!"); } } } public class InheritInner extends WithInner.Inner { //! InheritInner() {} // Won't compile InheritInner(WithInner wi) { // 语法enclosingClassReference.super();是java处理内部类继承时的特殊语法, // 非内部类上下文中的使用都会出错;enclosingClassReference.super(); // 与非内部类中super();语句的其中一个作用是一样的,都控制转向了对象实例化的流程 wi.super(); } public static void main(String[] args) { WithInner wi = new WithInner(); InheritInner ii = new InheritInner(wi); } }
结果:
匿名内部类
匿名内部类必须实现或继承外部类或接口。
public class AnonymousClass2 { class Con{ } public Con getCon(){ return new Con(){ int i=5; public String toString(){ return "Con toString"+i; } }; } public static void main(String[]args){ System.out.println(new AnonymousClass2().getCon()); } }