Java

java枚举类型enum用法有哪些

小云
96
2023-08-30 12:32:57
栏目: 编程语言

Java中枚举类型(enum)的用法有以下几种:

  1. 定义枚举类型:使用关键字"enum"定义枚举类型,并在{}内列出枚举常量。
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. 枚举构造函数:枚举类型可以有构造函数,并且只能在枚举常量中调用。
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
看了该问题的人还看了