【问题标题】:class StatusCode extends Enum<StatusCode>类 StatusCode 扩展 Enum<StatusCode>
【发布时间】:2023-04-01 17:13:01
【问题描述】:
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>

如果我不能明确地扩展 Enum 类,为什么不呢?这不是最终类,是什么确保不能扩展枚举类?

【问题讨论】:

  • every enum is subclass of the class Enum。对我来说,这听起来你已经知道如何从Enum 继承。你有什么困惑?
  • 枚举是一个抽象类,它不是最终的。那么为什么不允许我扩展枚举类呢?

标签: java generics inheritance enums


【解决方案1】:

错误信息说得很清楚:

StatusCode 类型不能显式继承 Enum&lt;StatusCode&gt;

你需要做的,只是创建一个enum类型:

enum StatusCode { ONE, TWO; }

有了这个enum,编译器确保它扩展了Enum&lt;StatusCode&gt;,你不必担心它。

你可以通过运行这个测试 sn-p 来验证这是真的:

StatusCode statusCode = StatusCode.ONE;
System.out.println(statusCode instanceof Enum);

请注意,instanceof 运算符不需要Enum 的类型参数,您可以通过查看this thread 了解更多信息。

【讨论】:

    【解决方案2】:

    我在 Java 语言规范中找不到确切的定义。不过我能找到的是§8.9里面的这句话(可能里面没有直接写):

    The final clone method in Enum ensures that enum constants can never be
    cloned, and the special treatment by the serialization mechanism ensures that
    duplicate instances are never created as a result of deserialization. 
    Reflective instantiation of enum types is prohibited. Together, these four 
    things ensure that no instances of an enum type exist beyond those defined by 
    the enum constants.
    

    如果您可以通过简单地扩展 Enum-class 来定义枚举,则将违反此声明。 因此,要回答您的问题,只需编译器禁止扩展枚举即可。

    【讨论】:

      【解决方案3】:

      枚举是一个抽象类,它不是最终的。那么为什么不允许我扩展枚举类呢?

      枚举是语言的一部分,因此适用特殊规则。这在Java Language Specification 8.1.4

      中明确排除

      如果 ClassType 将类命名为 Enum 或对 Enum 的任何调用,则会出现编译时错误

      此规则必须存在,否则您可以这样做:

      public class EnumButNotAnEnum extends Enum<EnumButNotAnEnum> {
      
          @Override
          public EnumButNotAnEnum(String name, int ordinal) {
              super(name, ordinal);
          }
      
          // etc
      }
      

      换句话说,您可以创建Enum 的子类,这些子类可以有无限的实例。

      【讨论】:

        猜你喜欢
        • 2018-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-14
        • 1970-01-01
        • 1970-01-01
        • 2016-10-10
        • 2014-08-01
        相关资源
        最近更新 更多