Java 枚举类的使用方法如下:
enum
定义枚举类,枚举值以逗号分隔,并以分号结束。例如:public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Weekday day = Weekday.MONDAY;
name()
方法获取枚举值的名称:String name = day.name(); // 返回 "MONDAY"
==
运算符比较枚举值。例如:if (day == Weekday.MONDAY) {
// 执行某些操作
}
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
Weekday day = Weekday.SATURDAY;
boolean isWeekend = day.isWeekend(); // 返回 true
枚举类还支持其他一些特性,例如可以在枚举值上定义字段和构造函数,以及实现接口等。