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