What is the usage of Java enumeration?
A Java enumeration class is a special type of class used to define a set of constants. Each constant in an enumeration class is an instance of the class and can be accessed by its name.
Enumerations can be used to define a group of related constants, such as days of the week, months of the year, gender, etc. Enumerations are commonly used in programming to replace constant values, improving the readability and maintainability of the code.
The usage of an enumerated class is as follows:
- Define an enumeration class: use the keyword enum to define an enumeration class, and then list all the constants within the enumeration class.
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
- Accessing enumeration constants: Enumeration constants can be accessed by using the constant names of the enumeration class.
Day day = Day.MONDAY;
System.out.println(day); // 输出 MONDAY
- Enumerated constants can be directly used in a switch statement or as a method parameter.
switch(day) {
case MONDAY:
System.out.println("Today is Monday");
break;
case TUESDAY:
System.out.println("Today is Tuesday");
break;
// other cases...
}
Overall, the use of Java enumeration classes can improve code readability, reduce errors, and make the code easier to maintain and expand.