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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…