class OpenSource {
private int x;
public OpenSource(int x) {
this.x = x;
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
static OpenSource Open(OpenSource opensource) {
opensource = new OpenSource(100); //line 19
return opensource;
}
public static void main(String a[]) {
OpenSource open = new OpenSource(300); //line 24
System.out.println(open.getX() + ".");
OpenSource opensource = Open(open); //line 26
System.out.println(open.getX() + ".");
System.out.println(opensource.getX() + ".");
open = Open(opensource);
System.out.println(open.getX() + ".");
System.out.println(opensource.getX());
}
}
//为什么输出产生300 300 100 100 100为什么不300 100 100 100 100我错了?
我已经绘制了如下表示来理解它。
答案 0 :(得分:0)
在你的函数Open
中,你有这一行:
opensource = new OpenSource(100); //line 19
但这里的opensource
变量实际上只是传递的对象位置的副本。更改位置的副本不会改变原始位置,这不是您可以用Java做的事情。
让我们看看这个稍微简单的例子:
public static Integer addOne(Integer in) {
in = in + 1;
return in;
}
// ... sometime later
Integer three = Integer.valueOf(3);
Integer four = addOne(three);
在此示例中,我们希望变量three
仅保留值3
,即使在addOne
内部我们修改变量in
,我们也是不更新变量three
,只更新名为three
的变量in
的副本。