Java - Enum with abstract method

Introduction

The following code adds abstract method getValue() to MyEnum type.

An abstract method for an enum type forces you to override that method.

The body of each constant overrides and provides implementation for the getValue() method.

Demo

enum MyEnum {
  C1 {/*from  ww w.  j  av  a  2 s .  c o  m*/
    // Body of constant C1
    public int getValue() {
      return 100;
    }
  },
  C2 {
    // Body of constant C2
    public int getValue() {
      return 10;
    }
  },
  C3 {
    // Body of constant C3
    public int getValue() {
      return 0;
    }
  };

  // Provide default implementation for getValue() method
  public abstract int getValue();
}

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

Result

Related Topic