阅读量:0
在Java中,枚举类型使用enum
关键字来定义。枚举类型可以包含常量、方法和构造函数。以下是枚举类型的一些使用方法:
- 定义枚举类型:
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
- 访问枚举常量:
Day day = Day.MONDAY; System.out.println(day); // 输出 MONDAY
- 使用枚举类型中的方法:
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; public boolean isWeekend() { return this == SATURDAY || this == SUNDAY; } } Day day = Day.SATURDAY; System.out.println(day.isWeekend()); // 输出 true
- 使用
values()
方法获取枚举常量数组:
Day[] days = Day.values(); for (Day day : days) { System.out.println(day); }
- 使用
valueOf()
方法根据字符串获取枚举常量:
Day day = Day.valueOf("MONDAY"); System.out.println(day); // 输出 MONDAY
- 实现枚举类型的构造函数和方法:
public enum Day { MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday"); private String displayName; Day(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } } Day day = Day.MONDAY; System.out.println(day.getDisplayName()); // 输出 Monday