可能重複:
Cannot access static field within enum initialiser爲什麼我無法在構造函數中訪問枚舉中的靜態字段?
我的情況:
enum Attribute { POSITIVE, NEGATIVE }
enum Content {
C1(Attribute.POSITIVE),
C2(Attribute.POSITIVE),
... // some other positive enum instances.
Cm(Attribute.NEGATIVE),
... // some other negative enum instances.
Cn(Attribute.NEGATIVE);
private final Atrribute a;
static int negativeOffset = 0;
private Content(Atrribute a) {
this.a = a;
if (a.compareTo(Attribute.POSITIVE) == 0) {
negativeOffset ++;
}
}
public static int getNegativeOffset() { return negativeOffset; }
}
我的目的是通過一個每當我添加一個新的枚舉(正屬性)來添加negativeOffset,那麼我可以調用getNegativeOffset()來獲得負數 enum的起始點並執行任何我想要的操作。
但comlier抱怨
Cannot refer to the static enum field Content.negativeOffset within an initializer
HTTP的
Attribute
枚舉值的簡單比較:// stackoverflow.com/questions/536449/cannot-refer-to-the-static-enum-field-within-an-initializer 這將有所幫助。 – LPD