首页 > 解决方案 > 为什么在我的 java 代码中声明 a=b+c 后我得到 a 的默认值

问题描述

包 abc;

公共类测试{

public static void main(String[] args) {
    // TODO Auto-generated method stub
    A n= new A();
System.out.println(n.b);

System.out.println(nc); nj ();

}

} 类 A {

int b;
int c;
A(){
    b=3;
    c=8;
    
    
} int a=b+c;
void j() {
    System.out.println(a);
}

}

标签: javaclassobjectvariablesdefault-value

解决方案


您在声明中添加b和. 因此,在的实例初始化期间,该算术与and (就在它们之后)同时完成。cabcnA

初始化类实例时的指令顺序是先初始化字段变量,然后调用构造函数 A ()。它们不是出现在程序行中的顺序。

所以顺序是

enter the program at main ()
call the constructor new A ()
the "new" knows that it has to initialize the fields first
initialize b (to 0)
initialize c (to 0)
initialize a to b + c (to 0 = 0 + 0)
start running the actual constructor A ()
set b to 3
set c to 8
exit the constructor
return to main ()
print n.b
exit the program

请注意, a 的值是在构造函数之外计算的。因此,请调整您的展示位置,以便执行您想要的正确订单。

这种遍历代码是消除错误的好方法。很快你就会像第二天性一样在你的脑海中做这件事。


推荐阅读