java - Java 通过值或引用传递?有人可以帮我处理这段代码吗?
问题描述
我有这个代码。当我运行它时,我得到了这个结果:
圆 A:中心 X:5,中心 Y 5,半径 5
圆 B:中心 X:10,中心 Y 10,半径 10
改变
圆 A:中心 X:10,中心 Y 10,半径 5
圆 B:中心 X:5,中心 Y 5,半径 10
如果java不允许将值作为参考传递,这段代码是如何允许的?
以防万一,当我用调试器查看它时,对象“autre”的方向与对象 A 相同。
public class Main {
public static void main(String[] args) {
Cercle A = new Cercle();
Cercle B = new Cercle();
A.creer(5, 5, 5);
System.out.println("The Circle A : ");
A.show();
B.creer(10, 10, 10);
System.out.println("The Circle B : ");
B.show();
System.out.println("Change");
B.change(A);
System.out.println("The Circle A : ");
A.show();
System.out.println("The Circle B : ");
B.show();
}
}
public class Cercle {
public int x, y;
public int r;
public void creer (int n1, int n2, int n3)
{
x = n1;
y = n2;
r = n3;
}
public void show()
{
System.out.println(" The center X: "+x+", the center Y "+y+" and the Radius "+r);
}
public void change(Cercle autre){
int tmp ;
tmp = x ;
x = autre.x;
autre.x = tmp;
tmp = y;
y = autre.y;
autre.y = tmp ;
}
}
解决方案
JAVA 确实是“按值传递”,但在这里,您将引用(的值)(仍然是该对象的地址)传递给函数中的对象,该对象本身就是一个引用。对其进行的任何更改也会更改原始对象。
这就像将指针作为参数传递给 C/C++ 中的函数,在该函数中传递指针的副本并对其进行修改,但是由于副本本身就是地址,因此您基本上修改了变量所在的地址,从而修改了变量反过来。
请参阅此内容以更详细地了解。
推荐阅读
- .net-core - 在asp.net core web api中通过swagger播放视频流
- microsoft-graph-api - 在新的限制限制下使用 Microsoft Graph API 上传大型附件
- html - 无法单击使用 Selenium 和 Java 的网站上的链接
- javascript - Html form does not show up
- c - 确定以下函数的复杂性 (Big O)
- reactjs - Redux Toolkit 和 Reactjs:切片中的更改触发在其他切片上订阅的组件上重新渲染
- r - R如何自动将字符输入强制转换为数字?
- excel - 使用vba计算到期日期
- pine-script - 仅当当前屏幕分辨率小于 60 分钟时才想使用函数“timeframe.period”显示 vwap
- javascript - 在 vue 中过滤 JSON 对象以计算新对象