java枚举如何使用
时间: 2024-04-24 15:17:56 浏览: 97
Java中的枚举是一种特殊的数据类型,用于定义一组固定的常量。以下是Java枚举的使用方法:
1. 定义枚举类型:使用关键字enum来定义一个枚举类型,然后在花括号内列出枚举常量。例如:
```java
enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
```
2. 使用枚举常量:可以直接使用枚举常量来表示一个特定的值。例如:
```java
Weekday today = Weekday.MONDAY;
System.out.println("Today is " + today);
```
3. 遍历枚举常量:可以使用for-each循环来遍历枚举常量。例如:
```java
for (Weekday day : Weekday.values()) {
System.out.println(day);
}
```
4. 添加属性和方法:枚举常量可以有自己的属性和方法。例如:
```java
enum Weekday {
MONDAY("星期一"), TUESDAY("星期二"), WEDNESDAY("星期三"), THURSDAY("星期四"), FRIDAY("星期五"), SATURDAY("星期六"), SUNDAY("星期日");
private String chineseName;
private Weekday(String chineseName) {
this.chineseName = chineseName;
}
public String getChineseName() {
return chineseName;
}
}
Weekday today = Weekday.MONDAY;
System.out.println("Today is " + today.getChineseName());
```
阅读全文