Enumerations
Now that we’ve covered the basics of classes, we can talk a bit more in depth about enumerations. As we’ve discussed, an enumeration is an object type in the Java language that is limited to an explicit set of values. The values have an order that is defined by their order of declaration in the code, and have a correspondence with a string name that is the same as their declared name in the source code.
We’ve already seen a couple of examples of enumerations used in place of static identifiers. For example:
enumWeekday{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}// usagesetDay(Weekday.Sunday);
Let’s take a look at what the Java compiler is actually generating
for the enum. It is a regular compiled Java class, in this case named
Weekday, so we can display it with the
javap command like so:
%javapWeekdaypublicfinalclassWeekdayextendsjava.lang.Enum{publicstaticfinalWeekdaySunday;publicstaticfinalWeekdayMonday;publicstaticfinalWeekdayTuesday;publicstaticfinalWeekdayWednesday;publicstaticfinalWeekdayThursday;publicstaticfinalWeekdayFriday;publicstaticfinalWeekdaySaturday;publicstaticfinalWeekday[]values();publicstaticWeekdayvalueOf(java.lang.String);}
Weekday is a subclass of the
Enum type with seven static, final,
“constant” object references corresponding to our seven enumerated values.
Each of the enumerated values is of type Weekday. The Java compiler does not let us extend this class or create ...