Can an enum have abstract methods?

前端 未结 4 643
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 13:11

Can an enum have abstract methods? If so, what is the use, and give a scenario which will illustrate this usage.

4条回答
  •  温柔的废话
    2020-12-05 13:34

    Just like @lukastymo 's answer, it is possible to implement an abstract method in enum and it is preferred to implement an interface when adding a method in an enum.

    From Java 8 and above, you can use lambda to implement methods in an enum for smaller code. These lambda can be executed outside the enum by exposing a public method that runs the given lambda.

    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 nextDateFunction; // or UnaryOperator
    
      ScheduleRepeat(Function nextDateFunction) {
        this.nextDateFunction = nextDateFunction;
      }
    
      public LocalDate calculateNextDate(LocalDate dateFrom) {
        return nextDateFunction.apply(dateFrom);
      }
    }
    

    Then the enum can be used like:

    LocalDate today = LocalDate.of(2019, 9, 18); // 2019 Sep 18
    ScheduleRepeat.DAILY.calculateNextDate(today); // 2019-09-19
    ScheduleRepeat.MONTHLY.calculateNextDate(today); // 2019-10-19
    

    This isn't exactly implementing an abstract method from the enum itself or from an interface, but I think this approach of adding method using lambda looks clean.

提交回复
热议问题