一. 定义枚举类
通过enum
关键字来定义枚举类,enum
定义的类型就是class
,只不过它有以下几个特点:
- 定义的
enum
类型总是继承自java.lang.Enum
,且无法被继承; - 只能定义出
enum
的实例,而无法通过new
操作符创建enum
的实例; - 定义的每个实例都是引用类型的唯一实例;
- 可以将
enum
类型用于switch
语句。
enum Weekday {
MON(1, "星期一"), TUE(2, "星期二"), WED(3, "星期三"), THU(4, "星期四"), FRI(5, "星期五"), SAT(6, "星期六"), SUN(0, "星期日");
public final int dayValue;
private final String chinese;
private Weekday(int dayValue, String chinese) {
this.dayValue = dayValue;
this.chinese = chinese;
}
@Override
public String toString() {
return this.chinese;
}
}
说明:如上定义了一个枚举类,每多一个枚举,需要一个唯一的数字和其一一对应,数字应该递增不重复。private Weekday(int value)
是一个只能在class
内部调用的构造函数。
二. 使用枚举类
在上面定义了一个星期的枚举类。
public class Main {
public static void main(String[] args) {
Weekday day = Weekday.SUN;
if (day == Weekday.SAT || day == Weekday.SUN) {
System.out.println(day + " Work at home!");
} else {
System.out.println(day + " Work at office!");
}
switch(day) {
case MON:
case TUE:
case WED:
case THU:
case FRI:
System.out.println(day + " Work at office!"); break;
case SAT:
case SUN:
System.out.println(day + " Work at home!"); break;
default:
throw new RuntimeException("cannot process " + day);
}
}
}
enum Weekday {
MON(1, "星期一"), TUE(2, "星期二"), WED(3, "星期三"), THU(4, "星期四"), FRI(5, "星期五"), SAT(6, "星期六"), SUN(0, "星期日");
public final int dayValue;
private final String chinese;
private Weekday(int dayValue, String chinese) {
this.dayValue = dayValue;
this.chinese = chinese;
}
@Override
public String toString() {
return this.chinese;
}
}