我肯定已经花了一个多小时试图找出某些意外行为的原因。最后,我意识到未按预期设置字段。在耸耸肩并继续前进之前,我想了解一下为什么这样做会如此。
在运行下面的示例时,我希望输出为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();
}
}
输出:
bool=false
boolean bool = true;
public ClassTwo() {
super();
}
等同于
boolean bool;
public ClassTwo() {
super();
bool = true;
}
编译器会自动在构造函数内移动字段初始化(紧接在超级构造函数调用之后,隐式或显式)。
由于布尔字段的默认值是false
,当super()
被调用when时(因此ClassOne()
和fireMethod()
),bool
尚未设置为true
。
有趣的事实:以下构造函数
public ClassTwo() {
super();
fireMethod();
}
将被理解为
public ClassTwo() {
super();
bool = true;
fireMethod();
}
由JVM,因此输出将是
bool=false
bool=true
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句