为什么枚举常量必须在枚举类型中的任何其他变量和方法声明之前声明? [英] Why the enum constants must be declared before any other variables and methods declaration in an enum type?
问题描述
枚举MyEnum
{
int i = 90;
}
它显示以下编译错误。
MyEnum.java:3:< identifier>预期
/ pre>
{
^
MyEnum.java:4:',','}'或';'预计
int i = 90;
^
MyEnum.java:4:'}'expected
int i = 90;
^
MyEnum.java:5:class,interface或enum expected
}
^
4个错误
但是,如果我在声明
i
之前声明一个枚举常量,那么它编译得很好。
即使以下代码可以正常编译:枚举MyEnum
{
; //放一个分号
int i = 90;
}
为什么java枚举是这样设计的?
解决方案
;
表示枚举识别符列表的结尾。显然你可以有一个空的枚举列表,但你必须有一个。
请参阅 8.9.1 /jls7.pdf\"> Java语言规范:
8.9.1枚举常量
枚举的正文类型可能包含枚举常量
If I declare a variable before or without declaring enum constants in this way:
enum MyEnum { int i = 90; }
It shows following compilation error.
MyEnum.java:3: <identifier> expected { ^ MyEnum.java:4: ',', '}', or ';' expected int i = 90; ^ MyEnum.java:4: '}' expected int i = 90; ^ MyEnum.java:5: class, interface, or enum expected } ^ 4 errors
But if I declare an enum constant before declaring
i
then it compiles fine.
Even the following code will compile fine:enum MyEnum { ;//put a semicolon int i = 90; }
Why java enum is designed in this way?
解决方案The
;
indicates the end of the enum identnfiers list. Apparently you can have an empty enum list, but you must have one.See 8.9.1 of the Java Language Specification:
8.9.1 Enum Constants The body of an enum type may contain enum constants
这篇关于为什么枚举常量必须在枚举类型中的任何其他变量和方法声明之前声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!