How do we use an enum type with a constructor in Java?



Enum type can have a private constructor that can be used to initialize instance fields. 

The EnumDemo class demonstrates this. It features a Food enum type with four constants: HAMBURGER, FRIES, HOTDOG, and ARTICHOKE. Notice that after each constant value is present in parentheses. This calls the constructor for that member to initialize the price field for that member. 

We iterate over the Food values in the for loop in the main() method. In this method, we first display the name of the food constant. Next, we examine the price for that food item and display whether the price is expensive or affordable. Following this, for fun, we demonstrate the use of a switch statement with the Food enum type.

Example:

public class EnumDemo {
   public enum Food {
      HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);
      Food(int price) {this.price = price;}
      private final int price;
      public int getPrice() {
         return price;
      }
}
public static void main(String[] args) {
   for (Food f : Food.values()) {
   System.out.print("Food: " + f + ", ");

      if (f.getPrice() >= 4) {
         System.out.print("Expensive, ");
      } else {
               System.out.print("Affordable, ");
   }
switch (f) {
      case HAMBURGER:
         System.out.println("Tasty");
      continue;
      case ARTICHOKE:
         System.out.println("Delicious");
      continue;
      default:
      System.out.println("OK");
    }
  }
 }
}

Output:

Food: HAMBURGER, Expensive, Tasty
Food: FRIES, Affordable, OK
Food: HOTDOG, Affordable, OK
Food: ARTICHOKE, Expensive, Delicious
raja
Published on 27-May-2019 16:35:55
Advertisements