public enum EnumTest implements DemoInterface {
private static int i = 5; // ❌ 編譯錯誤:靜態字段在枚舉常量之前
CONSTANT_A {
public int getI() { return i; }
public String getDesc() { return "A"; }
},
CONSTANT_B {
public int getI() { return i; }
public String getDesc() { return "B"; }
};
// 正確位置:枚舉常量結束後
private static int i = 5; // ✅ 編譯通過
}
Java 枚舉定義語法強制要求:
; 結束);錯誤原因:編譯器解析枚舉時,先處理常量列表,遇到非常量成員即報錯。將 private static int i = 5; 移至常量列表之後即可解決。