I am new to enums in java and I am confused as to why this code compiles fine
enum Scale5 {
GOOD(), BETTER(), BEST();
static Scale5 s=GOOD;
}
But this code fails:
enum Scale5 {
GOOD(), BETTER(), BEST();
Scale5 s=GOOD;
}
And I get the error : illegal reference to static field from initializer. I dont understand the reason.I am relatively inexperienced in enums so please dump it down for me.Thanks a lot!
The question asked here Cannot refer to the static enum field within an initializer? is the exact opposite of what I have asked.In my case declaring s as static compiles the code just fine.
Think of an enum like this:
public final class Scale5
{
public static final Scale5 GOOD = new Scale5();
public static final Scale5 BETTER = new Scale5();
public static final Scale5 BEST = new Scale5();
static Scale5 s = GOOD;//works because GOOD is initialized first;
Scale5 ss = GOOD;//doesn't work because in order to initialize GOOD,
//ss must be assigned an object that is not yet initialized;
}