在Java中,枚举类型是一种特殊的类,用于表示固定数量的常量值。要创建一个枚举类型,请按照以下步骤操作:
{}
。;
分隔。下面是一个简单的Java枚举类型示例,表示一周中的星期:
public enum DayOfWeek {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
// 枚举构造函数
private DayOfWeek() {
// 防止实例化
}
// 获取英文表示的方法
public String get英文表示() {
switch (this) {
case SUNDAY:
return "Sunday";
case MONDAY:
return "Monday";
case TUESDAY:
return "Tuesday";
case WEDNESDAY:
return "Wednesday";
case THURSDAY:
return "Thursday";
case FRIDAY:
return "Friday";
case SATURDAY:
return "Saturday";
default:
return "";
}
}
// 根据数字获取枚举常量的方法
public static DayOfWeek fromNumber(int number) {
switch (number) {
case 0:
return SUNDAY;
case 1:
return MONDAY;
case 2:
return TUESDAY;
case 3:
return WEDNESDAY;
case 4:
return THURSDAY;
case 5:
return FRIDAY;
case 6:
return SATURDAY;
default:
throw new IllegalArgumentException("Invalid number for DayOfWeek");
}
}
}
使用这个枚举类型的示例:
public class EnumExample {
public static void main(String[] args) {
// 使用枚举常量
System.out.println("Today is " + DayOfWeek.MONDAY);
// 使用枚举方法
System.out.println("英文表示: " + DayOfWeek.MONDAY.get英文表示());
// 根据数字获取枚举常量
int number = 3;
DayOfWeek day = DayOfWeek.fromNumber(number);
System.out.println("Number " + number + " represents: " + day);
}
}
输出:
Today is MONDAY
英文表示: Monday
Number 3 represents: WEDNESDAY