Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-如何使用方法更改引用?_Java_Reference - Fatal编程技术网

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

Java-如何使用方法更改引用?,java,reference,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

我试图更改对象的引用,并编写了以下代码

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
方法中没有改变。为什么?

在Java中,方法的所有参数都是按值传递的。注意,作为对象引用的非原语类型的变量也按值传递:在这种情况下,引用按值传递


因此,在您的情况下,您在函数中所做的修改不会更改主函数中使用的对象

我不知道您所说的“更改对象的引用”是什么意思,但我强烈怀疑您的问题会得到回答,以至于我很想将其作为副本关闭。@Reimeus标记的副本不正确。问题是关于传递参考资料。在Java中,引用作为副本传递到方法中。任何重新分配仅限于该范围。