我一定花了一个多小时试图找出一些意外行为的原因。我最终意识到字段没有按我的预期设置。在耸耸肩并继续之前,我想了解为什么会这样。
在运行下面的示例时,我希望输出为 true,但它是 false。其他测试表明我总是得到该类型的默认值。
public class ClassOne {
public ClassOne(){
fireMethod();
}
protected void fireMethod(){
}
}
public class ClassTwo extends ClassOne {
boolean bool = true;
public ClassTwo() {
super();
}
@Override
protected void fireMethod(){
System.out.println("bool="+bool);
}
public static void main(String[] args) {
new ClassTwo();
}
}
output:
bool=false
boolean bool = true;
public ClassTwo() {
super();
}
与
boolean bool;
public ClassTwo() {
super();
bool = true;
}
编译器自动在构造函数内移动字段初始化(在超级构造函数调用之后,隐式或显式)。
由于布尔字段默认值为false
, when super()
被称为(因此ClassOne()
and fireMethod()
), bool
尚未设置为true
yet.
有趣的事实:以下构造函数
public ClassTwo() {
super();
fireMethod();
}
将被理解为
public ClassTwo() {
super();
bool = true;
fireMethod();
}
由 JVM 执行,输出将是
bool=false
bool=true
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)