Java

java枚举使用的方法是什么

小亿
82
2024-05-24 09:10:13
栏目: 编程语言

在Java中,枚举类型使用enum关键字来定义。枚举类型可以包含常量、方法和构造函数。以下是枚举类型的一些使用方法:

  1. 定义枚举类型:
public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
  1. 访问枚举常量:
Day day = Day.MONDAY;
System.out.println(day); // 输出 MONDAY
  1. 使用枚举类型中的方法:
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
  1. 使用values()方法获取枚举常量数组:
Day[] days = Day.values();
for (Day day : days) {
    System.out.println(day);
}
  1. 使用valueOf()方法根据字符串获取枚举常量:
Day day = Day.valueOf("MONDAY");
System.out.println(day); // 输出 MONDAY
  1. 实现枚举类型的构造函数和方法:
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

0
看了该问题的人还看了