Access to static fields
in enum constructor is forbidden by the compiler. Below source code works:). It uses 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.
This does not work. Difference is very small:
public enum TrickyEnum
{
TrickyEnum1, TrickyEnum2;
static int count;
TrickyEnum()
{
count++; //compiler error
}
public static void main(String... args)
{
System.out.println("Count: " + count);
}
}
As I searched internet, usually people answered the problem is connected with order of initializing static fields
.But first example works, so why do java developers forbid second example? It should also work.