版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Vermont_/article/details/84312005
Java始终是按值传递的。但是,我们通常将对象的位置称为“引用”。当我们传递一个对象的值时,我们将引用传递给它。这对初学者来说很困惑。
我们可以通过两个例子来看一下:
它是这样的:
public static void main(String[] args) {
Dog aDog = new Dog("Max");
// 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
}
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
}
在上面的例子中aDog.getName()
仍将返回"Max"
。main函数内的aDog值在foo函数内未发生改变,
"Fifi"对象是作为对象引用来传值的。如果它是通过引用传递的,在调用foo函数后,则aDog.getName()
将在调用后返回"Fifi"。
同样:
public static void main(String[] args) {
Dog aDog = new Dog("Max");
foo(aDog);
// when foo(...) returns, the name of the dog has been changed to "Fifi"
aDog.getName().equals("Fifi"); // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// this changes the name of d to be "Fifi"
d.setName("Fifi");
}
在上面的例子中,Fifi
调用后是狗的名字,foo(aDog)
因为对象的名字是在里面设置的foo(...)
。foo
执行的任何对于d的操作都是在aDog
自身上执行的(除非d
更改为指向不同的Dog
实例d = new Dog("Boxer")
)。