Java始终是按值传递的。 不幸的是,当我们传递一个对象的值时,我们将引用传递给它。 这对初学者来说很不友好。
它是这样的:
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
}
在上面的示例中,aDog.getName()仍将返回“Max”。 使用Dog“Fifi”在函数foo中不更改main中的值aDog,因为对象引用按值传递。 如果它是通过引用传递的,那么main中的aDog.getName()将在调用foo后返回“Fifi”。
同样:
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");
}
在上面的例子中,Fifi是调用foo(aDog)之后的狗的名字,因为对象的名字是在foo(...)中设置的。 foo在d上执行的任何操作都是这样的,出于所有实际目的,它们是在aDog上执行的,但是不可能更改变量aDog本身的值。
Java的工作方式与C完全相同。可以分配指针,将指针传递给方法,按照方法中的指针操作并更改指向的数据。但是,我们无法更改指针指向的位置。
在C ++,Ada,Pascal和其他支持pass-by-reference的语言中,实际上可以更改传递的变量。
如果Java具有pass-by-reference语义,那么我们在上面定义的foo方法会更改myDog在BBB上分配someDog时指向的位置。
将引用参数视为传入的变量的别名。当分配该别名时,传入的变量也是如此。