Java - Add a different body to each enum constant.

Introduction

The body can have fields and methods.

The body for an enum constant is placed inside braces following its name.

If the enum constant accepts arguments, its body follows its argument list.

Syntax

The syntax for associating a body to an enum constant is as follows:

<access-modifier> enum <enum-type-name> {
        CONST1 {
                // Body for CONST1 goes here
        },
        CONST2 {
                // Body for CONST2 goes here
        },
        CONST3(arguments-list) {
                // Body of CONST3 goes here
        };

        // Other code goes here
}

Consider an MyEnum enum type, as shown:

enum MyEnum {
        C1 {
                // Body of constant C1
                public int getValue() {
                        return 100;
                }
        },
        C2,
        C3;
}

The following code declares a getValue() method for the MyEnum enum type, which returns 0.

The C1 constant overrides the getValue() method and returns 100.

C2 and C3 do not have to have a body, they do not need to override the getValue() method.

You can use the getValue() method on the each value of MyEnum enum type.

Demo

enum MyEnum {
  C1 {//from ww w .j  a v a2s  .co m
    // Body of constant C1
    public int getValue() {
      return 100;
    }
  },
  C2, C3;

  // Provide the default implementation for the getValue() method
  public int getValue() {
    return 0;
  }
}

// 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