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”。值aDog内main未在功能改变foo与Dog “Fifi”作为对象基准由值来传递。如果是通过引用传递的,则
aDog.getName()inmain将”Fifi”在调用之后返回foo。
同样地:
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本身。



