首页 > 解决方案 > 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 ;
    }

}

标签: javaobject

解决方案


JAVA 确实是“按值传递”,但在这里,您将引用(的值)(仍然是该对象的地址)传递给函数中的对象,该对象本身就是一个引用。对其进行的任何更改也会更改原始对象。

这就像将指针作为参数传递给 C/C++ 中的函数,在该函数中传递指针的副本并对其进行修改,但是由于副本本身就是地址,因此您基本上修改了变量所在的地址,从而修改了变量反过来。

请参阅内容以更详细地了解。


推荐阅读