在var初始化期间使用this.var [英] Using this.var during var's initialization
本文介绍了在var初始化期间使用this.var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在研究另一个问题时,我惊讶地发现以下Java代码编译时没有错误:
While researching another question, I was surprised to discover that the following Java code compiles without errors:
public class Clazz {
int var = this.var + 1;
}
在我的JDK6中, var
初始化为 1
。
In my JDK6, var
gets initialized to 1
.
上述代码是否具有明确定义的语义,或者其行为是否未定义?如果您说它定义明确,请引用 JLS 的相关部分。
Does the above code have well-defined semantics, or is its behaviour undefined? If you say it's well-defined, please quote the relevant parts of the JLS.
推荐答案
在 8.3.2.3节。在示例的文本中
class Z {
static int peek() { return j; }
static int i = peek();
static int j = 1;
}
class Test {
public static void main(String[] args) {
System.out.println(Z.i);
}
}
标题说:
... i的变量初始值设定项使用类方法peek在j变量初始化之前访问变量j 的值初始值设定项,此时它仍然具有默认值(§4.12.5)。
这应直接映射到您的情况。
This should map directly to your situation.
这篇关于在var初始化期间使用this.var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文