Java Legal Forward Referencing [英] 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:
- 设置
x
并且y
为零,因为这是int
s的默认值。 - 通过调用
getValue()
初始化x
,该值读取y $的值C $ C>。由于
y
尚未初始化,因此它仍然具有值0。 - 初始化
y
到5。
- Set
x
andy
to zero, since that's the default value forint
s. - Initialize
x
by callinggetValue()
, which reads the value ofy
. Sincey
hasn't yet been initialized, it still has the value 0. - 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屋!