请原谅我,我正在尝试理解这个概念,不想在不知道发生了什么的情况下就接受它。 我读到只有类 X 的对象可以修改自身,从下面的代码来看,Class 事实上ModifyX可以通过调用setNum方法来改变X.x.num。
我的问题是:
[ModifyX
object "mx"] 为何能够更改 X
中的 [ X
object "x"] 值?
作为参数传递的 y 值在 X 中发生了更改,但为什么它在 main(String[] args)
中没有更改?
public class X {
private int num;
public void setNum(int num) {
this.num = num;
}
public void getNum() {
System.out.println("X is " + num);
}
public static void main(String[] arsgs) {
int y = 10;
X x = new X();
x.setNum(y); //sets the value of num in X to y;
x.getNum(); // print the value of num in X
ModifyX mx = new ModifyX(); // A new class that is inteded to modify X
mx.changeX(x); //calls the set method of X with new Value 5
x.getNum(); // returns the new Value passed in changeX instead of y
System.out.println("Integer Y is not changed = " + y); // but y still remains the same
}
}
class ModifyX {
public void changeX(X num) {
num.setNum(5); // changes y to 5
}
}
最佳答案
这个方法
s.setNum(y);
获取值y
的副本并将其传递给该方法。 Java 始终是按值传递的,因此它始终会传递值的浅拷贝。这意味着您可以更改此值的任一副本,而不会影响另一个副本。
这个方法
num.setNum(5);
与
相同num.num = 5;
因此,此处仅更改了一个值,即 X num
的 num
字段。
您的局部变量 y
是 10
并且该变量在任何地方都没有更改,因此没有理由相信它应该更改。
关于java - 一个类如何在没有原始类对象的情况下更改另一个类值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35385338/