溫馨提示×

java枚舉類型enum用法有哪些

小云
94
2023-08-30 12:32:57
欄目: 編程語言

Java中枚舉類型(enum)的用法有以下幾種:

  1. 定義枚舉類型:使用關(guān)鍵字"enum"定義枚舉類型,并在{}內(nèi)列出枚舉常量。
enum Season {
SPRING, SUMMER, AUTUMN, WINTER
}
  1. 枚舉常量:枚舉類型中的每個常量都是枚舉類型的一個實例對象,可以通過常量名來訪問。
Season spring = Season.SPRING;
  1. 枚舉方法:枚舉類型可以定義自己的方法。
enum Season {
SPRING, SUMMER, AUTUMN, WINTER;
public void printSeason() {
System.out.println("This is " + this.name());
}
}
  1. 枚舉構(gòu)造函數(shù):枚舉類型可以有構(gòu)造函數(shù),并且只能在枚舉常量中調(diào)用。
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;
}
}
  1. 自定義屬性和方法:枚舉類型可以有自定義的屬性和方法。
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());
}
}
}
  1. 使用switch語句:可以使用switch語句對枚舉類型進行匹配。
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;
}

0