Enumerations are new features that Java 5 begins to support by defining a set of related constants in a type so that only these finite constants are used. First define an enumeration type that represents seven days a week as an example: Java code enum Weekday {SUNDAY, MONDAY, Tuesday, Wednsday, Thursday, FRIDAY, SATURDAY};
Enum Weekday {
SUNDAY, MONDAY, Tuesday, Wednsday, Thursday, FRIDAY, SATURDAY
};
This defines a weekday enumeration type, noting that the last semicolon can be omitted. Because there are only 7 members in the weekday, the weekday variable can take only one of the values, for example: Java code weekday WD = Weekday.monday;
Weekday WD = Weekday.monday;
This seems to be a simple enumeration type, which is essentially a class whose implied parent class is Java.lang.Enum, so weekday automatically inherits the method of the enum, two of which is useful, one called ordinal (), which returns the member's declaration order number, which is an integer , the value is numbered starting at 0, such as Weekday.SUNDAY.ordinal () returning 0, and Weekday.MONDAY.ordinal () returning 1. Another method, called name (), returns the name of the enumeration member.
More interestingly, the enumeration type can be used directly with the switch statement, which appears to break through the Java switch only for integers and characters, but is actually a smokescreen for the Java compiler, which automatically invokes the ordinal () method on the enumeration member. For example: Java code weekday WD = Weekday.friday; Switch (WD) {Case MONDAY:SYSTEM.OUT.PRINTLN ("This week is just beginning, slowly wait for it"); Break ... case FRIDAY:System.out.println ("Come over the weekend, enjoy it"); Break ... }
Weekday WD = Weekday.friday;
Switch (WD) {case
MONDAY:
System.out.println ("This week is just beginning, slowly wait");
break;
...
Case FRIDAY:
System.out.println ("Come over the weekend, enjoy it");
break;
...
}
If you're traversing weekday, you can use its implied static method values (), which cannot be defined in the document, which is added by the Java compiler, very strange. For example: Java code for (weekday Wd:Weekday.values ()) {SYSTEM.OUT.PRINTLN (wd + ", Order:" + wd.ordinal ()); }
for (weekday wd:Weekday.values ()) {
System.out.println (wd + ", Order:" + wd.ordinal ());
}
The above is the basic usage of enumerations, which are actually more complex in nature, such as defining constructors, defining fields, defining and overriding methods, and even overriding the methods in enumerations in the enumerated constants, which are described in the next article.