Java - Enum

Updated: 2019-01-27

A simple example: day of week

class Test {
  enum DayOfWeek {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
  }

  public static void main(String[] args) {
    System.out.println(DayOfWeek.FRIDAY); // => FRIDAY
  }
}

Java's enum is more like a class, it can have constructor and methods:

class Test {
  enum DayOfWeek {
    SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);

    private final int num;

    // constructor
    DayOfWeek(int num) {
      this.num = num;
    }

    // method
    public boolean isWeekDay() {
      return this != SUNDAY && this != SATURDAY;
      // or: return num >= 1 && num <= 5;
    }
  }

  public static void main(String[] args) {
    System.out.println(DayOfWeek.FRIDAY.isWeekDay()); // => true
    System.out.println(DayOfWeek.SUNDAY.isWeekDay()); // => false
  }
}