Java Enum Type Definition and Usage
In Java, an enum is a special data type that allows programmers to define their own enumeration types and use these types within programs. An enum type can be viewed as a collection of constants, where each constant has a name and a corresponding value.
In Java, an enum type is defined using the keyword enum, followed by specifying the name of the enum type and the constants it contains. For example, here is an example defining a color enum type:
enum Color {
RED, GREEN, BLUE;
}
In this example, Color is an enum type that contains three constants: RED, GREEN, and BLUE. These constants are all instances of the Color type and can be accessed via the enum type name and the constant name. For example:
Color c = Color.RED;
System.out.println(c); // Outputs RED
Enum types can also define constructors, member variables, and methods. For example, here is an example defining a day-of-the-week enum type:
enum DayOfWeek {
MONDAY("星期一"),
TUESDAY("星期二"),
WEDNESDAY("星期三"),
THURSDAY("星期四"),
FRIDAY("星期五"),
SATURDAY("星期六"),
SUNDAY("星期日");
private String chineseName;
private DayOfWeek(String chineseName) {
this.chineseName = chineseName;
}
public String getChineseName() {
return chineseName;
}
}
In this example, DayOfWeek is an enum type that contains seven constants: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY. Each constant has a corresponding Chinese name. A constructor and a member method getChineseName() are defined, which can be used to retrieve the Chinese name of a constant. For example:
DayOfWeek today = DayOfWeek.MONDAY;
System.out.println(today.getChineseName()); // Outputs "星期一"