可以為每個列舉常數新增一個不同的主體。主體可以有欄位和方法。列舉常數的主體放在其名稱後的大括號中。如果列舉常數接受引數,其主體將遵循其引數列表。將主體與列舉常數相關聯的語法如下:
<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