Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

illegal reference to static field from initializer

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.

like image 318
paidedly Avatar asked Mar 20 '15 19:03

paidedly


Video Answer


1 Answers

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.

like image 194
Sergey Pauk Avatar answered Nov 05 '22 17:11

Sergey Pauk