Possible Duplicate:
Cannot access static field within enum initialiser
My situation:
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; }
}
My intention is to add negativeOffset by one whenever I add a new enum(with POSITIVE attribute), then I could call the getNegativeOffset() to get the start point of negative
enum and do whatever I want.
But comlier complains that
Cannot refer to the static enum field Content.negativeOffset within an initializer
You can use this “trick”:
then refer to the variable like this:
and
The reason this works is that the JVM guarantees that the variable is initialized when the
IntHolderstatic inner class is initialized, which doesn’t happen until it’s accessed.The whole class will then be as follows, which compiles:
Note the corrections for spelling errors and the simpler comparison with the
Attributeenum value using==instead ofcompareTo()