Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an empty enum have abstract methods?

I accidentally discovered that the following doesn't compile in Eclipse:

enum Empty {
    ;
    abstract void foo();
}

The JLS seems to validate this behavior:

It is a compile-time error if an enum declaration E has an abstract method m as a member, unless E has at least one enum constant and all of E's enum constants have class bodies that provide concrete implementations of m.

I'm wondering what would be the reasoning behind this. Why not treat an empty enum as an abstract class with no existing implementations?

like image 892
shmosel Avatar asked Mar 16 '26 19:03

shmosel


1 Answers

As you correctly noted, specification requires that you have at least one enum constant in this case. That's because unlike usual abstract class with no existing implementation enum cannot be implemented somewhere else, thus such abstract method becomes completely useless.

For usual abstract class the implementation can be loaded later from other source, compiler cannot know about this. But for enum compiler is pretty sure that there's no implementation, so no reason to declare such method.

like image 109
Tagir Valeev Avatar answered Mar 18 '26 07:03

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!