1
package main;

public class Main {
    double radius;
    public Main(double newRadius) {
        radius = newRadius;
    }


    public static void main (String [] args) {
        Main x = new Main(1);
        Main y = new Main(2);
        Main temp;
        // try to swap first time
        temp = x;
        x = y;
        y = temp;
        System.out.println(x.radius + " " +  y.radius);
        x = new Main(1);
        y = new Main(2);
       // try to swap second time
        swap(x, y);
       System.out.println(x.radius + " " + y.radius);
    }
    public static void swap(Main x, Main y) {
        Main temp = x;
        x = y;
        y = temp;
    }

}

为什么第一次有效,第二次无效?第一个做了交换,但第二个没有。我正在传递对函数的引用。为什么这不起作用?

4

1 回答 1

0

您误解了如何传递引用,您创建了一个交换引用的范围,然后该范围结束。

尝试将字段的值存储在变量中,例如 temp = x.radius,然后分配给 y.radius。

第一次起作用的原因是作用域是一样的。

于 2018-11-10T13:14:26.437 回答