它不是通过引用传递的。相反,它是通过引用的值传递的,这是一个微妙但重要的区别。
After you mutate foo
in the rest of your main()
method, the foo
field will also exhibit these mutations, as you state, since both variables point to the same instance. However, if you reassign foo
to something new, the foo
field will not be changed. This would not be true if foo
were truly passed by reference. In short, everything is passed by value in Java; it just so happens that objects are dealt with by reference, and so the values of these references are passed.
I'll try to illustrate this with an example. Consider the following class:
class A {
public int n;
public A(int n) {
this.n = n;
}
}
and the following method:
public static void mutate(A a) {
a.n = 42;
}
Now we can have something like this:
A a = new A(0);
A.mutate(a);
System.out.println(a.n);
42
We can see that the state of a
was changed in mutate()
. Now let's modify the static method:
public static void mutate(A a) {
a = new A(42);
}
and try again:
A a = new A(0);
A.mutate(a);
System.out.println(a.n);
0
如您所见, 的状态a
没有改变。如果引用已被传递给函数,我们会期望重新分配的效果在方法范围之外是显而易见的。然而,实际上传递了一些引用,因为改变参数也会导致方法之外的变化。