0
public abstract class Enum<E extends Enum<E>>
    implements Comparable<E>, Serializable


class StatusCode extends Enum<StatusCode>

In java every enum is subclass of the class Enum. I want to inherit Enum class into my custom class 'StatusCode'. I have tried to do the same, but compiler throws an error. details are as follows

The type StatusCode may not subclass Enum<StatusCode> explicitly
    - Bound mismatch: The type StatusCode is not a valid substitute for the bounded parameter <E extends 
     Enum<E>> of the type Enum<E>

If I cannot extend Enum class explicitly why not? This is not a final class, what is making sure that enum class can't be extended ?

Babu Reddy H
  • 186
  • 1
  • 11

3 Answers3

3

The error message says it clear:

The type StatusCode may not subclass Enum<StatusCode> explicitly.

What you need to do, is just to create an enum type:

enum StatusCode { ONE, TWO; }

Having this enum, the compiler makes sure it extends Enum<StatusCode> and you don't have to worry about it.

You can verify this is true by running this test snippet:

StatusCode statusCode = StatusCode.ONE;
System.out.println(statusCode instanceof Enum);

Note that the instanceof operator doesn't need the type-parameter for Enum, which is a topic you can learn more about by checking out this thread.

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

Enum is an abstract class and its not final. So why I am not allowed to extend the enum class?

Enums are part of the language, so special rules apply. This is ruled out explicitly in the Java Language Specification 8.1.4

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

It is essential for this rule to exist because otherwise you could do this:

public class EnumButNotAnEnum extends Enum<EnumButNotAnEnum> {

    @Override
    public EnumButNotAnEnum(String name, int ordinal) {
        super(name, ordinal);
    }

    // etc
}

In other words, you could create subclasses of Enum that could have unlimited instances.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
0

I don't find the exact definition in Java Language specification. However what I can find is this sentence in §8.9 (Maybe it is not written directly inside):

The final clone method in Enum ensures that enum constants can never be
cloned, and the special treatment by the serialization mechanism ensures that
duplicate instances are never created as a result of deserialization. 
Reflective instantiation of enum types is prohibited. Together, these four 
things ensure that no instances of an enum type exist beyond those defined by 
the enum constants.

This statement would be violated if you could define an enum by simply extending Enum-class. So to answer your question it is simply the compiler to prohibit extension of enum.

Denis Lukenich
  • 3,084
  • 1
  • 20
  • 38