Access to static fields in enum constructor is forbidden by the compiler. The source code below works, it uses a static field:
public enum TrickyEnum
{
TrickyEnum1, TrickyEnum2;
static int count;
TrickyEnum()
{
incrementCount();
}
private static void incrementCount()
{
count++;
}
public static void main(String... args)
{
System.out.println("Count: " + count);
}
}
Output:
Count: 2.
But the code below does not work despite there being very little difference:
public enum TrickyEnum
{
TrickyEnum1, TrickyEnum2;
static int count;
TrickyEnum()
{
count++; //compiler error
}
public static void main(String... args)
{
System.out.println("Count: " + count);
}
}
From my search, people usually claim that the problem is due to the order in which static fields are initialized. But first example works, so why do Java developers forbid the second example? It should also work.