在Java中,枚舉類型是一種特殊的類,用于表示固定數量的常量值。要定義一個枚舉類型,請遵循以下步驟:
enum
開始定義一個新的枚舉類型。以下是一個簡單的Java枚舉類型示例,表示一周中的星期:
public enum DayOfWeek {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
// 可選:添加一個方法
public String getFullName() {
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 class Main {
public static void main(String[] args) {
DayOfWeek today = DayOfWeek.FRIDAY;
System.out.println("Today is " + today);
System.out.println("Full name of " + today + " is " + today.getFullName());
}
}