Java - Add text description and custom value fields to a Enum type

Introduction

The following code would add text description to each enum constant.

Ad it also sets custom value for each enum value.

To force you to provide those two value it declares a constructor.

Demo

enum Level {
  LOW("Low Priority", 30) {
    public double getCustom() {
      return 1000.0;
    }/*from   w  w  w .ja  v a  2  s .  co m*/
  },
  MEDIUM("Medium Priority", 15) {
    public double getCustom() {
      return 2000.0;
    }
  },
  HIGH("High Priority", 7) {
    public double getCustom() {
      return 3000.0;
    }
  },
  URGENT("Urgent Priority", 1) {
    public double getCustom() {
      return 5000.0;
    }
  };

  // Declare instance variables
  private String description;
  private int index;

  // Declare a private constructor
  private Level(String description, int i) {
    this.description = description;
    this.index = i;
  }

  public int getIndex() {
    return index;
  }

  // Override the toString() method in the Enum class to return description
  @Override
  public String toString() {
    return this.description;
  }

  // Provide getCustom() abstract method, so all constants
  // override and provide implementation for it in their body
  public abstract double getCustom();
}

public class Main {
  public static void main(String[] args) {
    for (Level s : Level.values()) {
      String name = s.name();
      String desc = s.toString();
      int ordinal = s.ordinal();
      int i = s.getIndex();
      double projectedCost = s.getCustom();
      System.out.println("name=" + name + ", description=" + desc
          + ", ordinal=" + ordinal + ", days=" + i + ", projected cost="
          + projectedCost);
    }
  }
}

Result

Related Example