共计 954 个字符,预计需要花费 3 分钟才能阅读完成。
在 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
丸趣 TV 网 – 提供最优质的资源集合!
正文完