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.
From Java Language Specification:
It is a compile-time error to reference a static field of an enum type that is not a constant variable (§4.12.4) from constructors, instance initializer blocks, or instance variable initializer expressions of that type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With