有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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>

如果我不能显式扩展枚举类,为什么不能?这不是最后一个类,是什么确保枚举类不能扩展


共 (3) 个答案

  1. # 1 楼答案

    我在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类来定义enum,则会违反此语句。 所以要回答你的问题,编译器只是禁止扩展枚举

  2. # 2 楼答案

    错误信息清楚地表明:

    The type StatusCode may not subclass Enum<StatusCode> explicitly.

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

    enum StatusCode { ONE, TWO; }
    

    有了这个enum,编译器确保它扩展了Enum<StatusCode>,而您不必担心它

    您可以通过运行以下测试片段来验证这一点:

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

    注意instanceof操作符不需要Enum的类型参数,这是一个可以通过签出this thread了解更多信息的主题

  3. # 3 楼答案

    Enum is an abstract class and its not final. So why I am not allowed to extend the enum class?

    枚举是语言的一部分,因此需要特殊规则。在Java Language Specification 8.1.4中明确排除了这一点

    It is a compile-time error if the ClassType names the class Enum or any invocation of Enum

    这条规则必须存在,否则你可能会这样做:

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

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