有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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方法在change方法中将foo1的引用从Foo@15db9742更改为Foo@6d06d69c,但在main方法中foo1的引用没有更改。为什么?


共 (1) 个答案

  1. # 1 楼答案

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

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