在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