How to use Java Enum class?
Java enum classes can be used by following these steps:
- a set of values that a variable can take
public enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
- Using enumerated constants: it is possible to access them by their enumerated constant name. For example:
DayOfWeek day = DayOfWeek.MONDAY;
System.out.println(day); // 输出: MONDAY
- By using enum classes, you can include methods that can be called through enum constants. For example:
public enum DayOfWeek {
// ...
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
DayOfWeek day = DayOfWeek.SATURDAY;
System.out.println(day.isWeekend()); // 输出: true
- Using static methods and properties in an enumeration: Enumerations can contain static methods and properties, which can be directly called using the enumeration name. For example:
public enum DayOfWeek {
// ...
public static DayOfWeek fromString(String dayStr) {
for (DayOfWeek day : DayOfWeek.values()) {
if (day.name().equalsIgnoreCase(dayStr)) {
return day;
}
}
throw new IllegalArgumentException("Invalid day of week: " + dayStr);
}
}
DayOfWeek day = DayOfWeek.fromString("monday");
System.out.println(day); // 输出: MONDAY
These are the basic steps for using Java enumeration classes, which can be expanded and customized as needed.