【问题标题】:Why i am getting default value of a after declaring a=b+c in my java code为什么在我的 java 代码中声明 a=b+c 后我得到 a 的默认值
【发布时间】:2021-09-12 04:33:44
【问题描述】:

包装 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);
}

}

【问题讨论】:

  • 请正确格式化您的代码。

标签: java class object variables default-value


【解决方案1】:

这可能会解决您的问题。

这是一个工作示例

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);
}
}

【讨论】:

  • 给一个人一条鱼,他们就有一顿饭。教一个人钓鱼,他们可以养家糊口。
【解决方案2】:

您在a 的声明中添加了bc。因此,在 n A 的实例初始化期间,该算术与 bc(紧随其后)同时完成。

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

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

【讨论】:

    【解决方案3】:

    在里面放一个调试点 int a = b+c 你会知道原因的。如果某些东西不起作用,请调试并查看它是否将您带到解决方案附近的某个地方。

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

    【讨论】:

      猜你喜欢
      • 2013-10-04
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多