Java 合法前向引用 [英] Java Legal Forward Referencing

查看:37
本文介绍了Java 合法前向引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是合法前向引用的情况吗?如果是,为什么?

Is the following code the case of legal forward referencing? if yes why?

public class MyClass
{
  private static int x = getValue();
  private static int y = 5;
  private static int getValue()
  {
    return y;
  }
  public static void main(String[] args)
  {
    System.out.println(x);
  }
}

推荐答案

您拥有的上述代码是完全合法的 Java.在 Java 中,静态字段的初始化如下:首先,将所有字段设置为其类型的默认值(0、falsenull),然后在它们的声明顺序.这意味着上面的代码可以保证执行以下操作:

The above code you have is perfectly legal Java. In Java, static fields are initialized as follows: first, all fields are set to the default for their type (0, false, or null), and then initialized in the order in which they are declared. This means that the above code is guaranteed to do the following:

  1. xy 设置为零,因为这是 ints 的默认值.
  2. 通过调用getValue()来初始化x,它读取y的值.由于 y 还没有被初始化,它的值仍然是 0.
  3. y 初始化为 5.
  1. Set x and y to zero, since that's the default value for ints.
  2. Initialize x by calling getValue(), which reads the value of y. Since y hasn't yet been initialized, it still has the value 0.
  3. Initialize y to 5.

这意味着 x 将采用值 0 而 y 将采用值 5.这种行为是可移植的并且有保证.你可以在这里看到这个.

This means that x will take the value 0 and y will take the value 5. This behavior is portable and guaranteed. You can see this here.

希望这有帮助!

这篇关于Java 合法前向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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