一丶什么场景下用枚举? 我们先看java文档中对什么时候使用枚举的建议

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

在需要表示一组固定的常量时,应该使用枚举类型。这包括自然枚举类型,例如太阳系中的行星,以及在编译时知道所有可能值的数据集,例如菜单上的选项、命令行标志等等。

在需要表示一组固定的常量时,应该使用枚举类型 :我们解析一下这句话,因为枚举是没有set方法不能手动设置值进去,然后属性都是用static final修饰,所以我们书写常量的名称都是全大写加驼峰形式表示,然后enum给我们提供了一个values的方法来获取所有常量。

所以根据枚举是无法变化的特点,当变量(尤其是方法参数)只能从一小组可能值中取出一个时,您应该始终使用枚举。例如类型常量(合同状态:“永久”、“临时”、“学徒”)或标志(“立即执行”、“延迟执行”)。

二丶枚举的一些进阶使用 枚举实现抽象方法

public enum Animal {
    CAT {
        public String makeNoise() { return "MEOW!"; }
    },
    DOG {
        public String makeNoise() { return "WOOF!"; }
    };

    public abstract String makeNoise();
}

枚举实现接口

public enum ScheduleRepeat {
  DAILY(date -> date.plusDays(1)),
  WEEKLY(date -> date.plusWeeks(1)),
  MONTHLY(date -> date.plusMonths(1)),
  QUARTERLY(date -> date.plusMonths(3)),
  BIANNUALLY(date -> date.plusMonths(6)),
  ANNUALLY(date -> date.plusYears(1)),
  ;

  private final Function<LocalDate, LocalDate> nextDateFunction; // or UnaryOperator<LocalDate>

  ScheduleRepeat(Function<LocalDate, LocalDate> nextDateFunction) {
    this.nextDateFunction = nextDateFunction;
  }

  public LocalDate calculateNextDate(LocalDate dateFrom) {
    return nextDateFunction.apply(dateFrom);
  }
}

我们可以直接使用这个枚举传入一个LocalDate实现增加一天一个月

LocalDate today = LocalDate.of(2022, 8, 20); // 2022 8 20
ScheduleRepeat.DAILY.calculateNextDate(today); // 2022-08-21
ScheduleRepeat.MONTHLY.calculateNextDate(today); // 2019-09-21

总结 一个小小的枚举其实有很多场景,我们可以结合多态,也可以结合JAVA8的函数式编程来定义枚举,小伙伴如果有其他的枚举骚操作欢迎在文章下面留言分享!!!