Why the order of declaration important for Java enums, I mean why does this give (compile time) errors
public enum ErrorCodes {
public int id;
Undefined;
}
but this one is fine:
public enum ErrorCodes {
Undefined;
public int id;
}.
1. What is the order of variables in Enum? Explanation: The order of appearance of variables in Enum is their natural order (the natural order means the order in which they are declared inside Enum type). However, the compareTo() method is implemented to order the variable in ascending order.
the difference with enum is that the order of the members matters. To implement this feature the compiler team would have to add new features that would explicitly specify that behavior.
values() is a static method of Enum , which always returns the values in same order.
We can use the natural sort order or sort by their properties. Any Enum type we create implements the Comparable interface. Below is an excerpt from the Java documentation. Enum<E> implements Comparable<E> via the natural order of the enum (the order in which the values are declared).
It's not a very satisfying answer, but it's just how enums are defined in Java. See section 8.9 Enums in The Java Language Specification.
Because this is the syntax for enums. It could allow different orders however this may have been open to mistakes such as forgetting to place a type on a field and turning it into a enum value.
EDIT: The reason I say they could be in any order is that fields, methods, initialisers and constructors can be in any order. I believe the restriction is valid if it is to reduce mistakes. Even though fields/constructors/methods can be in any order its very common to see them in that order for readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With