Java 合法前向引用 [英] 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
的值.由于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 合法前向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!