3

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?

shmosel
  • 49,289
  • 6
  • 73
  • 138

1 Answers1

2

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • Since when do we make compile errors for useless code? Even an unused local variable is only a warning. By your reasoning, why not make an empty enum illegal altogether? – shmosel Nov 12 '15 at 07:38
  • @shmosel, in java it's common practice. Try to write some code after `return` statement or after endless loop, for example. You will get "unreachable code" compilation error. Another example is [here](http://stackoverflow.com/q/31398444/4856258). In general Java is quite strict about useless code comparing to other languages like C++. – Tagir Valeev Nov 12 '15 at 08:00
  • there's a difference between unused code and unreachable code. – shmosel Nov 12 '15 at 08:06
  • @shmosel, also there's a difference between unused code and code which cannot be used at all and makes no sense. Anyways that's how it's specified. Discussing whether should it be specified this way or not would lead us to opinion-based talk. – Tagir Valeev Nov 12 '15 at 08:08
  • 1
    This restriction is particularly silly because *no* instance method in an empty enum can ever be called, so why single out abstract methods? – Reinstate Monica Oct 21 '16 at 15:41