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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...