[英]Abstract inner class within non-abstract outer class
I have a super-class A with an abstract inner-class Inner, with another class B that extends A. Why doesn't A force B to implement the abstract inner-class? 我有一个超类A和一个抽象内部类Inner,另一个超类B扩展了A。为什么A不能强制B实现抽象内部类?
I've already looked here , but it only specifies abstract methods in non-abstracts classes. 我已经看过这里了 ,但是它只在非抽象类中指定了抽象方法。 Does the same principle apply here?
同样的原则在这里适用吗?
public class A {
...
abstract class Inner {
...
}
}
public class B extends A {
...
// Isn't forcing me to implement Inner
}
An inner class, whether it's abstract or not, is basically syntactic sugar for a class that has a built-in reference to an instance of another class, its enclosing class. 内部类,不管它是否是抽象的,基本上是一个类的语法糖,该类具有对另一个类(其封闭类)的实例的内置引用。 The fact that it is nested simply adds potential accessibility restrictions.
嵌套的事实只会增加潜在的可访问性限制。 Other than that, it's just like any other class (minus a few other restrictions on
static
members). 除此之外,它就像其他任何类一样(减去对
static
成员的其他一些限制)。
In many situations, there is no need to implement A.Inner
. 在许多情况下,无需实现
A.Inner
。 I was recently working with a UI-free browser library for Java. 我最近正在使用Java的无UI浏览器库。 They had a class
Element
with subclasses like Anchor
, Input
, Span
, Script
, Style
. 他们有一个带有子类的
Element
类,例如Anchor
, Input
, Span
, Script
, Style
。 Surely you wouldn't want to be forced to implement, for example, all the subclasses of Element
? 当然,您不想被迫实现
Element
所有子类吗? This is particularly true when the superclass is a member of someone else's code. 当超类是其他人的代码的成员时,尤其如此。 Said superclass may have private methods referring to private subclasses.
所述超类可以具有引用私有子类的私有方法。
因为除非B中的某些代码试图实例化A.Inner,否则这将是毫无意义的限制,在这种情况下,现有规则将已经捕获了它。
If you define a new concrete class that extends an abstract class, it has to implement the methods. 如果您定义了一个扩展抽象类的新具体类,则它必须实现这些方法。 But you haven't defined a new concrete class that extends
Inner
. 但是您尚未定义扩展
Inner
的新具体类。 You've defined a new class B
that extends A
; 您已经定义了一个扩展
A
的新类B
; in a sense, B
inherits the Inner
class, but it's still abstract. 从某种意义上说,
B
继承了Inner
类,但它仍然是抽象的。 (You can say B.Inner
in some contexts, but from my testing it appears that the compiler treats it the same as A.Inner
.) (您可以在某些情况下说
B.Inner
,但是从我的测试看来,编译器将其与A.Inner
相同。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.