为什么枚举构造函数不能访问静态字段 [英] Why enum constructor can't access static field

查看:148
本文介绍了为什么枚举构造函数不能访问静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么枚举的构造函数不能访问静态字段?





enum Test {
  e1,e2;      

  int i=0;
  static int j=5;

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

在上述代码中,构造函数可以访问实例变量但是没有静态变量J.

In the above code the constructor can access the instance variable but not the static variable J.

我已经阅读了与其他作者相关的答案,都是在初始化J(静态字段)之前初始化e1和e2,但是根据java规范所有的静态字段
初始化时,该类加载到内存,即运行构造函数之前。
所以在运行Test()构造函数之前,必须初始化静态变量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) {
  }
}

根据这个参数,构造函数将在静态字段的初始化之前运行,并且正在运行,因为它是打印0(由于JVM执行了启动)。但没有编译错误或没有运行时问题。那么为什么同样的事情不会发生在枚举中。

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.

推荐答案

如果你想像你的枚举如何实际看起来像一个类,感觉:

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());
  }
}

打印:

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.

这篇关于为什么枚举构造函数不能访问静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆