微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我在我的 java 代码中声明 a=b+c 后得到 a 的默认值

如何解决为什么我在我的 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(n.c); n.j();

}

} A级 {

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

}

解决方法

这可能会解决您的问题。

这是一个工作示例

public class Test {

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

}
}


public class A {

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

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

初始化类的实例时的指令顺序是先初始化字段变量,然后调用构造函数 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 的值是在构造函数之外计算的。因此,请调整您的展示位置,以便执行您想要的正确订单。

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

,

放入调试点 int a = b+c 你会知道原因的。如果某些东西不起作用,请进行调试,看看它是否能帮助您找到接近解决方案的地方。

答案: 执行顺序是这样的。 实例变量首先被实例化,然后跟随构造函数。 这样,所有变量都没有初始化为代码中的值,因此为它们分配了默认值 0。因此,“a”得到 0,即使 b 和 c 稍后在构造函数中分配给一个值。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。