Java枚舉體

將主體添加到枚舉常量

可以爲每個枚舉常量添加一個不同的主體。主體可以有字段和方法。枚舉常量的主體放在其名稱後的大括號中。如果枚舉常量接受參數,其主體將遵循其參數列表。將主體與枚舉常量相關聯的語法如下:

<access-modifier> enum <enum-type-name>  { 
   ENUM_VALUE1  {
      // Body for ENUM_VALUE1  goes  here
   },
   ENUM_VALUE2  {
      // Body for ENUM_VALUE2  goes  here
   },
   ENUM_VALUE3(arguments-list)  {
      // Body of  ENUM_VALUE3  goes  here
   };

   // Other  code  goes  here
}

示例

以下代碼創建了Level枚舉類型和它的主體。

enum Level {
  LOW("Low Level", 30) {
    public double getDistance() {
      return 30.0;
    }
  },
  MEDIUM("Medium Level", 15) {
    public double getDistance() {
      return 15.0;
    }
  },
  HIGH("High Level", 7) {
    public double getDistance() {
      return 7.0;
    }
  },
  URGENT("Urgent Level", 1) {
    public double getDistance() {
      return 1.0;
    }
  };

  private int levelValue;
  private String description;

  private Level(String description, int levelValue) {
    this.description = description;
    this.levelValue = levelValue;
  }

  public int getLevelValue() {
    return levelValue;
  }

  @Override
  public String toString() {
    return this.description;
  }

  public abstract double getDistance();
}

public class Main {
  public static void main(String[] args) {
    for (Level s : Level.values()) {
      String name = s.name();
      String desc = s.toString();
      int ordinal = s.ordinal();
      int levelValue = s.getLevelValue();
      double distance = s.getDistance();
      System.out.println("name=" + name + ",  description=" + desc
          + ",  ordinal=" + ordinal + ", levelValue=" + levelValue
          + ", distance=" + distance);
    }
  }
}

Level枚舉有一個抽象方法getDistance()。每個實例常量都有一個實體爲getDistance()方法提供實現。它覆蓋了Enum類中的toString()方法。
執行上面的代碼,得到如下結果 -

name=LOW,  description=Low Level,  ordinal=0, levelValue=30, distance=30.0
name=MEDIUM,  description=Medium Level,  ordinal=1, levelValue=15, distance=15.0
name=HIGH,  description=High Level,  ordinal=2, levelValue=7, distance=7.0
name=URGENT,  description=Urgent Level,  ordinal=3, levelValue=1, distance=1.0