Java中枚舉類型(enum)的用法有以下幾種:
enum Season {
SPRING, SUMMER, AUTUMN, WINTER
}
Season spring = Season.SPRING;
enum Season {
SPRING, SUMMER, AUTUMN, WINTER;
public void printSeason() {
System.out.println("This is " + this.name());
}
}
enum Season {
SPRING("March to May"), SUMMER("June to August"), AUTUMN("September to November"), WINTER("December to February");
private String description;
Season(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
enum Season {
SPRING("March to May"), SUMMER("June to August"), AUTUMN("September to November"), WINTER("December to February");
private String description;
Season(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public static void printAllSeasons() {
for (Season season : Season.values()) {
System.out.println(season.getDescription());
}
}
}
Season season = Season.SPRING;
switch (season) {
case SPRING:
System.out.println("It's spring");
break;
case SUMMER:
System.out.println("It's summer");
break;
case AUTUMN:
System.out.println("It's autumn");
break;
case WINTER:
System.out.println("It's winter");
break;
}