What is the concept of enums in Java?
In Java, an enum (short for enumeration) is a special data type used to define a set of named constants. It provides a more structured and type-safe way to represent a related group of constants, making code easier to read and maintain.
The enum type in Java is defined as an enum class, which can contain multiple enum constants. Each enum constant is an instance object of the enum class and is pre-defined at the time of declaration. Enum constants are typically named in uppercase letters and separated by commas.
An enumeration class can include fields, methods, and constructors. Enum fields can be used to define properties of enumeration constants, methods can be used to manipulate enumeration constants, and constructors are used to create enumeration constants.
Enumerated types are type-safe when comparing constant values because each enumerated constant is unique. Enumerated types can also be used in switch statements, with each enumerated constant branching off.
Here is an example of an enumeration class:
enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class Main {
public static void main(String[] args) {
DayOfWeek day = DayOfWeek.MONDAY;
System.out.println(day); // 输出:MONDAY
}
}
In the example above, DayOfWeek is an enum class that contains a set of enum constants representing the days of the week. In the main method, we created an enum variable day of type DayOfWeek and initialized it to MONDAY. Finally, we printed the value of day, which displays as “MONDAY”.