Java中枚举类型(enum)的用法有以下几种:
1. 定义枚举类型:使用关键字"enum"定义枚举类型,并在{}内列出枚举常量。
```java
enum Season {
SPRING, SUMMER, AUTUMN, WINTER
}
```
2. 枚举常量:枚举类型中的每个常量都是枚举类型的一个实例对象,可以通过常量名来访问。
```java
Season spring = Season.SPRING;
```
3. 枚举方法:枚举类型可以定义自己的方法。
```java
enum Season {
SPRING, SUMMER, AUTUMN, WINTER;
public void printSeason() {
System.out.println("This is " + this.name());
}
}
```
4. 枚举构造函数:枚举类型可以有构造函数,并且只能在枚举常量中调用。
```java
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;
}
}
```
5. 自定义属性和方法:枚举类型可以有自定义的属性和方法。
```java
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());
}
}
}
```
6. 使用switch语句:可以使用switch语句对枚举类型进行匹配。
```java
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;
}
```