Why can't a class extend an enum?

后端 未结 5 1831
死守一世寂寞
死守一世寂寞 2021-01-17 10:18

I am wondering why in the Java language a class cannot extend an enum.

I\'m not talking about an enum extending an enum<

5条回答
  •  暖寄归人
    2021-01-17 11:01

    You can't extend an enum. They are implicitly final. From JLS § 8.9:

    An enum type is implicitly final unless it contains at least one enum constant that has a class body.

    Also, from JLS §8.1.4 - Superclasses and Subclasses:

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

    Basically an enum is an enumerated set of pre-defined constants. Due to this, the language allows you to use enums in switch-cases. By allowing to extend them, wouldn't make them eligible type for switch-cases, for example. Apart from that, an instance of the class or other enum extending the enum would be then also be an instance of the enum you extend. That breaks the purpose of enums basically.

提交回复
热议问题