Java Legal Forward Referencing [英] Java Legal Forward Referencing

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

问题描述

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

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, false null ),然后按声明的顺序初始化。这意味着上述代码保证执行以下操作:

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. 设置 x 并且 y 为零,因为这是 int s的默认值。

  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 Legal Forward Referencing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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