Why enum constructor can't access static field

enums, java

Solution

If you imagine how your enum would actually look as a class, it makes sense:

public class Test {
  // Imagine you cannot move these two statements:
  public static final Test e1 = new Test();
  public static final Test e2 = new Test();

  int i=0;
  static int j=5;

  private Test(){
    System.out.println(i+ " " + j);
  }

  static int getJ() {
    return j;
  }


  public static void main(String[] args) {
    System.out.println(Test.getJ());
  }
}

This prints:

0 0
0 0
5

If you can share a concrete example (rather than a theoretical one), we could suggest how to redesign the code to achieve the desired result, despite the static field limitations.

Problem

Possible Duplicate: Why can’t enum’s constructor access static fields? ``` enum Test { e1,e2; int i=0; static int j=5; Test(){ System.out.println(i+" "+j); } } ``` In the above code the constructor can access the instance variable but not the static variable J. I have read the answer relate to other author all are saying the e1 and e2 initialized before the initialization of J( static field), But according java spec all the static field initialized when ever the class loaded to memory, that is before running of the constructor. So before running of Test() constructor the static variable j must be initialized. I'm not able understand the restriction, can any body make me understand.I have already read the answer of the questions Why can't enum's constructor access static fields? But I am not happy with answer like :-The constructor is called before the static fields have all been initialized. Suppose if take another example with a simple class like enum ``` class Test{ public static final Test t=new Test(); static int a=5; Test(){ System.out.println(a); } public static void main(String[] args) { } } ``` Here according to there argument the constructor will run before the initialization of static field and it's running also as it's print 0(As JVM did the initilization). But no compilation error or no run time problem. Then why the same thing not happen with enum.

Original source

Related problems