Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

java - What makes the Enum class uninheritable?

I've been looking at the source code of the Enum class. It seems like a plain abstract class with a protected constructor to me. It's not final, it doesn't have any special annotations inside it and it doesn't use native code. And yet, it cannot be subclassed directly. In fact, the following code doesn't 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 should be forbidden. But technically, how do you enforce this behavior? Can a programmer create a similar non-final class that wouldn't allow direct subclassing despite having an accessible constructor?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's only invalid to extend Enum directly within the language. Any time you declare an enum, that does create a subclass of Enum.

The way the JLS prevents you from "manually" declaring a class which extends Enum is simply to prohibit it explicitly. From JLS section 8.1.4:

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

(Where ClassType is the type you're extending.)

Without that rule, your code would have been perfectly valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...