[英]Why does Java disallow subclasses which cannot access any constructors of its super class?
This question is mainly in reference to Luiggi's answer to this SO question: Why can you not inherit from a class whose constructor is private? 这个问题主要是参考Luiggi对这个SO问题的回答: 为什么不能从构造函数为private的类继承?
I understand that Java enforces that every subclass constructor must call one of its superclass's constructors. 我知道Java强制每个子类构造函数都必须调用其超类的构造函数之一。 If all the superclass's constructors are private, this is obviously not possible. 如果所有超类的构造函数都是私有的,那么这显然是不可能的。 So, if a subclass theoretically could inherit from a superclass with private constructors, the result would be that you couldn't call a constructor on the subclass. 因此,如果子类理论上可以从具有私有构造函数的超类继承,那么结果将是您无法在子类上调用构造函数。
But what if I never intend to create an instance of the subclass anyway? 但是,如果我从不打算创建子类的实例怎么办? For example, what if my subclass only adds static fields and methods, and I'm only interested in using the static fields and methods of the superclass? 例如,如果我的子类仅添加静态字段和方法,而我仅对使用超类的静态字段和方法感兴趣,该怎么办? Then I don't need a constructor for the subclass. 然后,我不需要为子类构造函数。
what if my subclass only adds static fields and methods, and I'm only interested in using the static fields and methods of the superclass 如果我的子类仅添加静态字段和方法,而我仅对使用超类的静态字段和方法感兴趣,该怎么办?
In that case you don't need inheritance - use composition ! 在那种情况下,您不需要继承-使用组合 !
You should seal your class by declaring it as final
. 您应该通过将其声明为final
来封闭您的课程。 Then it is guaranteed that no sub-classes can be made 这样就可以保证不能创建任何子类
If only adding subclasses and can only create the parent class, the child "class" is really just a helper class without adding any functionality/responsibilites/etc. 如果仅添加子类并且只能创建父类,则子“类”实际上只是一个辅助类,而没有添加任何功能/职责/等。 to the parent. 给父母 In many respects, it's meaningless. 在许多方面,它是没有意义的。
A subclass of this sort would not be a legitimate subclass. 这种子类将不是合法的子类。 Even if all of its fields and methods were declared static, it would inherit all of the fields and methods of all of its superclasses, all the way back up to Object. 即使将其所有字段和方法都声明为静态,它也将继承其所有超类的所有字段和方法,一直返回到Object。 And there are non-static methods in Object. 并且Object中有非静态方法。 So this subclass would have some set of non-static methods (and possibly fields) in its declaration. 因此,此子类在其声明中将具有一组非静态方法(可能还有字段)。
This subclass could then be used as a type of a field, variable, type parameter or method argument (ie anywhere a type can be used). 然后,可以将该子类用作字段,变量,类型参数或方法参数的类型(即,可以使用任何类型的类型)。 The compiler would have to keep track of the fact that this particular type could only be used in some restricted sense. 编译器必须跟踪这一特定类型只能在某种受限意义上使用的事实。 (Imagine a method that returned a value of this subclass for example). (例如,假设有一个方法返回了该子类的值)。
There are, I'm sure, many more gotcha's for this sort of thing. 我敢肯定,这类事情还有更多的陷阱。
So, bottom line, it would make writing a compiler really hard. 因此,最重要的是,这将使编写编译器非常困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.