Using a Body for Enum Constants - Java Language Basics

Java examples for Language Basics:enum

Description

Using a Body for Enum Constants

Demo Code

public class Main {
  public static void main(String[] args) {
    for (Level s : Level.values()) {
      String name = s.name();//from   ww  w.j  a v  a  2 s. com
      String desc = s.toString();
      int ordinal = s.ordinal();
      int projectedTurnaroundDays = s.getValue();
      double projectedCost = s.getProjectedCost();
      System.out.println("name=" + name + ", description=" + desc
          + ", ordinal=" + ordinal + ", turnaround days="
          + projectedTurnaroundDays + ", projected cost=" + projectedCost);
    }
  }
}

enum Level {
  LOW("Low Priority", 30) {
    public double getProjectedCost() {
      return 1000.0;
    }
  },
  MEDIUM("Medium Priority", 15) {
    public double getProjectedCost() {
      return 2000.0;
    }
  },
  HIGH("High Priority", 7) {
    public double getProjectedCost() {
      return 3000.0;
    }
  },
  URGENT("Urgent Priority", 1) {
    public double getProjectedCost() {
      return 5000.0;
    }
  };

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

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

  // Declare a public method to get the turn around days
  public int getValue() {
    return value;
  }

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

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

Result


Related Tutorials