为什么枚举常量必须在枚举类型中的任何其他变量和方法声明之前声明? [英] Why the enum constants must be declared before any other variables and methods declaration in an enum type?

查看:156
本文介绍了为什么枚举常量必须在枚举类型中的任何其他变量和方法声明之前声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 枚举MyEnum 
{
int i = 90;
}

它显示以下编译错误。

  MyEnum.java:3:< identifier>预期
{
^
MyEnum.java:4:',','}'或';'预计
int i = 90;
^
MyEnum.java:4:'}'expected
int i = 90;
^
MyEnum.java:5:class,interface或enum expected
}
^
4个错误
/ pre>

但是,如果我在声明 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆