Three Primary Benefits of ENUM
- When you use the enum type, you define a new class. Just as with any other class, you can include custom methods and fields in the class. This allows you to provide encapsulated functionality related to the enum type. For example, the following defines a class of enum type with the average latitude and longitude for U.S. states. It contains a custom method, distance, that calculates the distance between a latitude and longitude passed as parameters to the method.
import static java.lang.Math.*;
public enum State {
AK (61.3850,-152.2683),
AL (32.7990,-86.8073),
...
WV (38.4680,-80.9696),
WY (42.7475,-107.2085);
private final double latitude;
private final double longitude;
State(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
private double latitude() { return latitude; }
private double longitude() { return longitude; }
private static final double R = 6371;
double distance(double lat, double lng) {
// spherical law of cosines
return cos(sin(latitude)*sin(lat) + cos(latitude)*cos(lat) + cos(lng-longitude)) * R;
}
} - Because the enum type is a class, it enforces type matching to include matching against the set of constants defined in the enum. This prevents errors by ensuring that parameters to functions will always contain a value in the enum type class. For example, if a function requires a season as a parameter, the actual parameter passed to the function at runtime will be matched against the four permissible values defined by the enum:
public enum Season { SPRING, SUMMER, WINTER, FALL };
public function weather(enum Season) {
...
}; - The enum construct makes code easier to understand and maintain. By creating an enum construct of members with meaningful names, you document code as you create it. For example, declaring an enum called "Option" makes it easy to understand the cases in the "switch" statement:
enum Option { SAVE, DISCARD, CANCEL };
Option pick;
...
switch (pick) {
case SAVE:
break;
case DISCARD:
break;
case CANCEL:
break;
} - In Java, the compiler automatically inserts special methods into the class to make it easy to perform standard operations. For example, the compiler automatically inserts a method called "values" that returns an array of enum constant values in the order they were declared. This makes iteration over the enum values very easy, as in the following example:
for (Month m : Month.values()) {
System.out.printf("%s has %d days", m, m.numberOfDays());
}