Why the enum constants must be declared before any

2020-08-21 03:25发布

问题:

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?

回答1:

The ; indicates the end of the enum identifiers 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



回答2:

Two mandatory parts of enum is:

  1. enum identifiers;
  2. enum body.

You have to first declare enum identifiers list before enum body. Here, ; is showing the first part, as the first part is mandatory. If you ignore that, it will produce an compilation error. If you add ; then it will compile as you fulfill both the criteria.