Java - Enum with Data and Methods

Introduction

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.

Demo

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;
  }// w w  w .  ja  va 2s  .  c om

  // 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 = s.name();
      int ordinal = s.ordinal();
      int days = s.getMyCustomeValue();
      System.out.println("name=" + name + ", ordinal=" + ordinal + ", days="
          + days);
    }
  }
}

Result

Related Topics

Example