Enum in Java

Overview

Enum is a short time of Enumeration. It is used to define a set of values that is not going to change in future e.g. days of a week. 
  • Example of simple Enum
 public enum DaysOfTheWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
 public static void main(String[] args) {
DaysOfTheWeek day = DaysOfTheWeek.FRIDAY;
if (day == DaysOfTheWeek.FRIDAY) {
System.out.println("Yay! Tomorrow is Saturday.");
}
for (DaysOfTheWeek myDay : DaysOfTheWeek.values()) {
System.out.println(myDay);
}
}
  • Example of Enum with Constructor
 public enum Burgers {
CHICKEN_BURGER(3, 15.10),
VEG_BURGER(5, 12.25),
EGG_BURGER(4, 13.50),
KING_BURGER(4, 20.25);

final int rating;
final double price;

Burgers(int rating, double price) {
this.rating = rating;
this.price = price;
}
}
 public static void main(String[] args) {
for (Burgers burger : Burgers.values()) {
System.out.println("Burger Name: " + burger + ", Rating: " + burger.rating + ", Price: " + burger.price);
}
}

Do's and Dont's

  • Enums can have a property and a constructor. 
  • If you define a constructor of an Enum then you have to modify every members of that Enum

Reference



Comments