java - 为什么在我的 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);
}
}
解决方案
您在声明中添加b
和. 因此,在的实例初始化期间,该算术与and (就在它们之后)同时完成。c
a
b
c
n
A
初始化类实例时的指令顺序是先初始化字段变量,然后调用构造函数 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 的值是在构造函数之外计算的。因此,请调整您的展示位置,以便执行您想要的正确订单。
这种遍历代码是消除错误的好方法。很快你就会像第二天性一样在你的脑海中做这件事。
推荐阅读
- gradle - 如何使用 gradle 将 jar 从 artifactory 下载到项目目录?
- c - C地址中的静态变量用法不同
- scala - 如何根据 IntelliJ IDEA 中提供的参数生成方法或构造函数参数名称
- android - 从 MvvM 架构和 Kotlin 中的广播接收器更新片段 ui
- linux-kernel - 未生成 Linux PCI 设备中断
- php - Laravel Eloquent 对关系进行多次计数
- gitlab - Gitlab“存在”规则不考虑工件
- django - PUT 请求的 Django Rest Framework 单元测试
- java - 组件扫描基础包未拾取组件/存储库导致依赖注入问题
- c# - 如何为.net framework 4.7.2做JWT Bearer API安全