Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a class extend an enum?

I am wondering why in the Java language a class cannot extend an enum.

I'm not talking about an enum extending an enum (which can't be done, since java doesn't have multiple inheritance, and that enums implicitly extend java.lang.Enum), but a class that extends an enum in order to only add extra methods, not extra enumeration values.

Something like:

enum MyEnum
{
    ASD(5),
    QWE(3),
    ZXC(7);
    private int number;
    private asd(int number)
    {
        this.number=number;
    }
    public int myMethod()
    {
        return this.number;
    }
}

class MyClass extends MyEnum
{
    public int anotherMethod()
    {
        return this.myMethod()+1;
    }
}

To be used like this:

System.out.println(MyClass.ASD.anotherMethod());

So, can anyone provide a rationale (or point me to the right JLS section) for this limitation?

like image 267
Unai Vivi Avatar asked Oct 17 '13 17:10

Unai Vivi


1 Answers

You can't extend an enum. They are implicitly final. From JLS § 8.9:

An enum type is implicitly final unless it contains at least one enum constant that has a class body.

Also, from JLS §8.1.4 - Superclasses and Subclasses:

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

Basically an enum is an enumerated set of pre-defined constants. Due to this, the language allows you to use enums in switch-cases. By allowing to extend them, wouldn't make them eligible type for switch-cases, for example. Apart from that, an instance of the class or other enum extending the enum would be then also be an instance of the enum you extend. That breaks the purpose of enums basically.

like image 164
Rohit Jain Avatar answered Sep 28 '22 22:09

Rohit Jain