// 定义一个枚举类,表示一周中的每一天
public enum DayOfWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
// 枚举类可以包含方法
public boolean isWeekend() {
return this == SUNDAY || this == SATURDAY;
}
// 枚举类也可以包含构造函数和实例变量
private final String description;
// 构造函数是私有的
DayOfWeek() {
this.description = "";
}
// 可以为每个枚举常量提供不同的描述
public String getDescription() {
switch (this) {
case MONDAY:
return "Start of the work week";
case FRIDAY:
return "End of the work week";
case SATURDAY:
return "Start of the weekend";
case SUNDAY:
return "End of the weekend";
default:
return "Mid-week day";
}
}
}
// 使用枚举类的示例
public class EnumExample {
public static void main(String[] args) {
DayOfWeek today = DayOfWeek.MONDAY;
System.out.println("Today is " + today);
System.out.println("Is today a weekend? " + today.isWeekend());
System.out.println("Description: " + today.getDescription());
// 遍历枚举常量
for (DayOfWeek day : DayOfWeek.values()) {
System.out.println(day + ": " + day.getDescription());
}
}
}
DayOfWeek
是一个枚举类,表示一周中的每一天。枚举类使用 enum
关键字定义。SUNDAY, MONDAY, ...
是枚举常量,每个常量代表一周中的一天。isWeekend()
用于判断当前是否为周末。description
是一个实例变量,用于存储每个枚举常量的描述。EnumExample
类中展示了如何使用枚举类,包括获取枚举常量、调用方法以及遍历所有枚举常量。下一篇:java执行linux命令行
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站