enum 是 JDK 1.5 引入的特殊參考型別,用於表示固定常數集合。所有枚舉隱含繼承 java.lang.Enum,不可再繼承其他類別,但可實作介面。
enum 關鍵字宣告private,不可外部呼叫values()、valueOf(String) 等靜態方法public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass; // kg
private final double radius; // m
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
public static final double G = 6.67300E-11; // 萬有引力常數
public double surfaceGravity() {
return G * mass / (radius * radius);
}
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet ");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight / EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass));
}
}
$ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 Your weight on MARS is 66.279007 Your weight on JUPITER is 442.847567 Your weight on SATURN is 186.552719 Your weight on URANUS is 158.397260 Your weight on NEPTUNE is 199.207413
| 方法 | 說明 |
|---|---|
values() | 回傳所有枚舉常數陣列,順序與宣告一致 |
valueOf(String name) | 依名稱取得對應常數,找不到拋出異常 |
ordinal() | 回傳常數宣告順序(從 0 開始) |
name() | 回傳常數名稱字串 |
compareTo(E o) | 比較兩枚舉常數順序 |
public interface Behavior { void print(); }
public enum Color implements Behavior {
RED("紅"), GREEN("綠"), BLUE("藍");
private String cnName;
Color(String cn) { this.cnName = cn; }
public void print() { System.out.println(cnName); }
}
// 使用
Color.RED.print(); // 輸出:紅
enum Singleton { INSTANCE; }int 常數,提供型別安全與可讀性EnumSet、EnumMap 高效處理集合操作