java - 解释这段代码中发生了什么?(帮助解释类)
问题描述
我正在学习 Java 编程课程,但我无法理解这段代码到底发生了什么。有人可以帮助更好地解释吗?
public class Foo {
private int x;
public Foo(int x) {
this.x = x;
}
public void printVals(int x) {
System.out.println(this.x);
System.out.println(x);
}
public static void main(String[] args) {
int x = 2;
Foo a = new Foo(x);
x += 4;
Foo b = new Foo(x);
x--;
--x;
a.printVals(x);
x -= x;
b.printVals(x);
x += 1;
System.out.println(x);
}
}
解决方案
public class Foo {
private int x; //line 2
public Foo(int x) {
this.x = x;
}
public void printVals(int x) {
System.out.println(this.x); //this.x == line 2.x
System.out.println(x);//x==parameter x<-(int x)
}
public static void main(String[] args) {
int x = 2; //local x == 2
Foo a = new Foo(x);//a.x==2
x += 4; //local x==6
Foo b = new Foo(x);//b.x==6
x--;//local x==5
--x;//local x==4
a.printVals(x);////a.x==2 && local x==4
x -= x;//local x == 0
b.printVals(x);//b.x==6 && local x ==0
x += 1;//local x==1
System.out.println(x);//local x==1
}
}
推荐阅读
- bash - bash中的空测试
- android - Amplify Android - 在第一次成功后,客户端发出了对“Amplify.configure”的后续调用
- android - Android admob 有时不显示
- javascript - 防止特定的默认操作
- azure-data-factory - 如何使基于 IF 任务的 Azure 数据工厂管道失败
- python - 如何在 python pandas 的列中进行条件操作?
- java - 提供一个空列表给一个可选的?
- entity-framework - “LINQ 在哪里”的最佳方式
- “ 什么时候
- 有很多元素吗?
- typescript - 尝试访问数据库时,带有 `Electron` 的 `TypeORM` 会导致“浏览器环境不支持此选项/功能”错误
- google-cloud-storage - 无法将 GCS 存储桶从一个帐户转移到另一个帐户