Java is always pass-by-value .
(Java总是按值传递 。)
Unfortunately, when we pass the value of an object, we are passing the reference to it. (不幸的是,当我们传递一个对象的值时,我们正在传递对该对象的引用 。)
This is confusing to beginners. (这使初学者感到困惑。)
It goes like this:
(它是这样的:)
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
// we pass the object to foo
foo(aDog);
// aDog variable is still pointing to the "Max" dog when foo(...) returns
aDog.getName().equals("Max"); // true
aDog.getName().equals("Fifi"); // false
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// change d inside of foo() to point to a new Dog instance "Fifi"
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}
In the example above aDog.getName()
will still return "Max"
.
(在上面的示例中, aDog.getName()
仍将返回"Max"
。)
The value aDog
within main
is not changed in the function foo
with the Dog
"Fifi"
as the object reference is passed by value. (main
的值aDog
不会在功能foo
中用Dog
"Fifi"
更改,因为对象引用是通过值传递的。)
If it were passed by reference, then the aDog.getName()
in main
would return "Fifi"
after the call to foo
. (如果通过引用传递,则main
的aDog.getName()
将在对foo
的调用之后返回"Fifi"
。)
Likewise:
(同样地:)
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
foo(aDog);
// when foo(...) returns, the name of the dog has been changed to "Fifi"
aDog.getName().equals("Fifi"); // true
// but it is still the same dog:
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// this changes the name of d to be "Fifi"
d.setName("Fifi");
}
In the above example, Fifi
is the dog's name after call to foo(aDog)
because the object's name was set inside of foo(...)
.
(在上面的示例中, Fifi
是调用foo(aDog)
之后的狗的名字,因为该对象的名称是在foo(...)
内部设置的。)
Any operations that foo
performs on d
are such that, for all practical purposes, they are performed on aDog
, but it is not possible to change the value of the variable aDog
itself. (任何操作是foo
上执行d
是这样的,对于所有的实际目的,它们被执行aDog
,但它是不可能改变的变量的值aDog
本身。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…