I am finding it tuff with enums. This is an example from Kathy Siera book :
public class WeatherTest {
static Weather w;
public static void main(String[] args) {
System.out.print(w.RAINY.count + " " + w.Sunny.count + " ");
}
}
enum Weather {
RAINY, Sunny;
int count = 0;
Weather() {
System.out.print("c ");
count++;
}
}
The output is c c 1 1. Understood.
Now I thought what if the count field was static? Would the output be c c 2 2 ?
Based on it, I modified the count variable to static.
But then what I see is this :
Compile Time Error : Illegal reference to static field from initializer.
Searching on net I found this was some kind of a loop-hole by Sun and it allows static methods that can change static fields. Ok.. So now I use a static method incr to do my job :
class WeatherTest {
static Weather w;
public static void main(String[] args) {
System.out.print(w.RAINY.count + " " + w.Sunny.count + " ");
}
}
enum Weather {
RAINY, Sunny;
Weather() {
System.out.print("c ");
incr();
}
static int count = 0;
static void incr() {
count++;
}
}
To my surprise, I get the output : c c 0 0 !
Can anyone please explain this behaviour to me before I shoot myself?
Enum values can be thought of as glorified static fields ( they are under the covers ).
So, if your
Weatherwere a regular Java class, it would have been something like this:You can see that
countis declared AFTER both enum values, that means it is also initialized after both values are created. Also, each function call that encounters uninitialized static variable treats it as initialized with default value ( forintit’s0).Because you never call
incraftercounthas been properly initialized, you see its value as still0