Java面向对象设计 – 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
}
例子
下面的代码用body创建了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);
}
}
}
级别枚举有一个抽象方法getDistance()。
每个实例常量都有一个实体为getDistance()方法提供实现。
它重写了Enum类中的toString()方法。
上面的代码生成以下结果。

国外主机测评 - 国外VPS,国外服务器,国外云服务器,测评及优惠码













