What makes the Enum class unacceptable?

I looked at the source code of the Enum class . It looks like a simple abstract class with a protected constructor. This is not the final version, it does not have any special annotations, and it does not use its own code. And yet it cannot be subclassed directly. In fact, the following code does not compile:

 class Foo<E extends Enum<E>> extends Enum<E> { Foo(String name, int ordinal) { super(name, ordinal); } } 

I know that Enum is a special class in Java, and I understand that there are good reasons why direct subclassing is forbidden. But technically, how do you apply this behavior? Can a programmer create a similar non-finite class that would not allow a direct subclass, despite the presence of an accessible constructor?

+4
source share
1 answer

This is not valid for Enum extensions directly inside the language. Each time you declare an Enum that subclasses Enum .

As JLS forbids you to β€œmanually” declare a class that extends Enum , simply prohibit it explicitly. From JLS section 8.1.4 :

This is a compile-time error if ClassType calls the Enum class or any call to it.

(Where ClassType is the type you are extending.)

Without this rule, your code would be absolutely right.

+6
source

Source: https://habr.com/ru/post/1500856/


All Articles