Java - Enum with Data and Methods


Since an enum type is a class type, you can add methods to an enum type.

The following code add custom value to each enum value via constructor.

The constructor is private and cannot be used outside the Level enum body.

We also added a getter method to return the custom value.


enum Level {
  LOW(30), MEDIUM(15), HIGH(7), URGENT(1);

  // Declare an instance variable
  private int myCustomeValue;

  // Declare a private constructor
  private Level(int c) {
    this.myCustomeValue = c;
  }//from   ww  w  .  j  a  v a  2 s  .  co m

  // Declare a public method to get the value
  public int getMyCustomeValue() {
    return myCustomeValue;

// prints the names of the constants, their ordinals, and their custom value.
public class Main {
  public static void main(String[] args) {
    for (Level s : Level.values()) {
      String name =;
      int ordinal = s.ordinal();
      int days = s.getMyCustomeValue();
      System.out.println("name=" + name + ", ordinal=" + ordinal + ", days="
          + days);


Related Topics