java类StatusCode扩展了枚举<StatusCode>
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable
class StatusCode extends Enum<StatusCode>
在java中,每个枚举都是类Enum
的子类。我想将Enum
类继承到我的自定义类“StatusCode”中。我也尝试过这样做,但编译器抛出了一个错误。详情如下:
The type StatusCode may not subclass Enum<StatusCode> explicitly
- Bound mismatch: The type StatusCode is not a valid substitute for the bounded parameter <E extends
Enum<E>> of the type Enum<E>
如果我不能显式扩展枚举类,为什么不能?这不是最后一个类,是什么确保枚举类不能扩展
# 1 楼答案
我在Java语言规范中找不到确切的定义。然而,我能在§8.9中找到这句话(可能不是直接写在里面):
如果可以通过简单地扩展enum类来定义enum,则会违反此语句。 所以要回答你的问题,编译器只是禁止扩展枚举
# 2 楼答案
错误信息清楚地表明:
您需要做的只是创建一个
enum
类型:有了这个
enum
,编译器确保它扩展了Enum<StatusCode>
,而您不必担心它您可以通过运行以下测试片段来验证这一点:
注意
instanceof
操作符不需要Enum
的类型参数,这是一个可以通过签出this thread了解更多信息的主题# 3 楼答案
枚举是语言的一部分,因此需要特殊规则。在Java Language Specification 8.1.4中明确排除了这一点
这条规则必须存在,否则你可能会这样做:
换句话说,您可以创建
Enum
的子类,这些子类可以有无限的实例