我一定花了一个多小时试图找出某些意外行为的原因。我最终意识到一个字段没有按照我的预期设置。在耸耸肩继续前进之前,我想了解为什么会这样。
在运行下面的示例时,我希望输出为真,但结果为假。其他测试表明我总是得到该类型的默认值。
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;
}
编译器会自动在构造函数中移动字段初始化(就在 super 构造函数调用之后,隐式或显式)。
由于 boolean 字段默认值为 false
,当 super()
被调用时(因此 ClassOne()
和 fireMethod ()
), bool
还没有设置为 true
。
有趣的事实:下面的构造函数
public ClassTwo() {
super();
fireMethod();
}
将被理解为
public ClassTwo() {
super();
bool = true;
fireMethod();
}
由 JVM,因此输出将是
bool=false
bool=true
关于java - 当从 super() 运行方法时,为什么不将字段初始化为非默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657877/