Member field order in Enum

Why declaration order is important for Java enums, I mean why this gives (compile time) errors

public enum ErrorCodes {
    public int id;
    Undefined;
}

but it normal:

public enum ErrorCodes {
    Undefined;
    public int id;

}.
+5
source share
3 answers

Because this is the syntax for the listings. It can allow different orders, but it can be open to errors, such as forgetting to put a type in a field and turn it into an enumeration value.

EDIT: , , , , , , . , , . // , , .

+5

, , Java. . 8.9 Enums Java.

+6

Java Enum - . :

public enum ErrorCodes {
    Undefined, Defined, Foo, Bar
}

, :

public class ErrorCodes {
    public final static ErrorCodes Undefined = new ErrorCodes();
    public final static ErrorCodes Defined = new ErrorCodes();
    public final static ErrorCodes Foo = new ErrorCodes();
    public final static ErrorCodes Bar = new ErrorCodes();
}

enum.

The sun was so kind that it allowed us to add fields that follow the definition of eunum members: public enum ErrorCodes {Undefined, Defined, Foo, Bar; private String myField; }

That is why your custom code should always be defined after the enumeration fields.

+1
source

All Articles