Java - 如何使用方法更改引用?

时间:2017-07-31 21:56:22

标签: java reference

我正在尝试更改对象的引用,并编写了以下代码。

public class Test {
    public static void main(String[] args) {
        Foo foo1 = new Foo();
        Foo foo2 = new Foo();
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
        System.out.println();
        change(foo1, foo2);
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
    }

    public static void change(Foo foo1, Foo foo2) {
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
        System.out.println();
        foo1 = foo2;
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
        System.out.println();
    }
}

class Foo {
    public Foo() {
        // do nothing
    }
}

我得到了以下输出。

the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c

the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c

the reference of foo1 is Foo@6d06d69c
the reference of foo2 is Foo@6d06d69c

the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c

change方法在foo1方法中将Foo@15db9742的引用从Foo@6d06d69c更改为change,但foo1的引用已更改不改变main方法。为什么呢?

1 个答案:

答案 0 :(得分:1)

在Java中,方法的所有参数都按值传递。请注意,非基本类型的变量(它们是对象的引用)也通过值传递:在这种情况下,引用按值传递。

因此,在您的情况下,您在函数中执行的修改不会更改主要

中使用的对象