Java知识123

怎么继承一个非静态的内部类?

2017-06-19  本文已影响6人  奔跑的笨鸟

如果某些情况下,如要继承一个内部类,现实中可能不会有这种要求。
一个包含内部类的类

class WithInner {
     class Inner {
    }
}

我们这样直接继承好像会有错误的。

/错误信息:
//Multiple markers at this line
//- No enclosing instance of type WithInner is available due to some intermediate constructor invocation
//- Breakpoint:F
public class F extends WithInner.Inner {
    
}

大概意思需要一个引用外部类WithInner 的构造方法。我们修改如下,就能顺利通过编译。

public class F extends WithInner.Inner {
    public F(WithInner withInner) {
        withInner.super();
    }

}

实际上原理可以简单理解为,一个非静态内部类的实例必须有一个外部类的引用。
如果内部类是静态的,其实就不需要外部类的实例了。

class WithInner {
     static class Inner {
    }
}


public class F extends WithInner.Inner {


}
上一篇 下一篇

猜你喜欢

热点阅读