无意中发现Eclipse中不能编译:
enum Empty {
;
abstract void foo();
}
JLS似乎验证了这种行为:
It is a compile-time error if an enum declaration E has an
abstract
methodm
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 ofm
.
我想知道这背后的原因是什么。为什么不将空枚举视为没有现有实现的抽象类?
最佳答案
正如您正确指出的那样,规范要求您在这种情况下至少有一个枚举常量。这是因为不像通常的抽象类,没有现有的实现枚举不能在其他地方实现,因此这种抽象方法变得完全无用。
对于通常的抽象类,实现可以稍后从其他来源加载,编译器无法知道这一点。但是对于枚举,编译器很确定没有实现,所以没有理由声明这样的方法。
关于java - 为什么空枚举不能有抽象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33665442/