在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());
}
}