Java 枚舉類型(Enum)是一種特殊的類,用于表示固定數量的常量值。枚舉類型可以實現一些功能,例如:
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
private int dayNumber;
public Weekday(int dayNumber) {
this.dayNumber = dayNumber;
}
public int getDayNumber() {
return dayNumber;
}
public void setDayNumber(int dayNumber) {
this.dayNumber = dayNumber;
}
public String getDayOfWeek() {
switch (this) {
case MONDAY:
return "Monday";
case TUESDAY:
return "Tuesday";
case WEDNESDAY:
return "Wednesday";
case THURSDAY:
return "Thursday";
case FRIDAY:
return "Friday";
case SATURDAY:
return "Saturday";
case SUNDAY:
return "Sunday";
default:
throw new IllegalStateException("Unknown day: " + this);
}
}
}
public class EnumExample {
public static void main(String[] args) {
Weekday today = Weekday.FRIDAY;
System.out.println("Today is " + today.getDayOfWeek());
System.out.println("Day number: " + today.getDayNumber());
today = Weekday.WEDNESDAY;
System.out.println("Today is " + today.getDayOfWeek());
System.out.println("Day number: " + today.getDayNumber());
}
}
在這個例子中,我們定義了一個名為 Weekday
的枚舉類型,它表示一周的七天。我們還為這個枚舉類型添加了一個構造函數、一個 getDayNumber()
方法和一個 getDayOfWeek()
方法。然后,在 EnumExample
類的 main
方法中,我們使用了這個枚舉類型來表示今天是星期幾以及它是星期幾的數字。