Java始终按值传递参数,而不按引用传递参数。
让我通过一个
public class Main{ public static void main(String[] args) { Foo f = new Foo("f"); changeReference(f); // It won't change the reference! modifyReference(f); // It will change the object that the reference variable "f" refers to! } public static void changeReference(Foo a) { Foo b = new Foo("b"); a = b; } public static void modifyReference(Foo c) { c.setAttribute("c"); }}我将逐步解释这一点:
1- 声明一个名为
ftype的引用,
Foo并将其分配给具有属性的
type的新对象。
Foo"f".
Foo f = new Foo("f");2- 从方法方面,声明
Foo具有名称的类型引用, 并将其初始分配给。
a null
public static void changeReference(Foo a)
3- 调用方法时
changeReference,引用a将分配给作为参数传递的对象。
changeReference(f);
4- 声明一个名为
btype的引用,
Foo并将其分配给具有属性的
type的新对象。
Foo"b".
Foo b = new Foo("b");5-
a = b正在将引用aNOT分配给 属性为f的对象。
"b"
6-调用
modifyReference(Foo c)方法时,将c创建一个引用并将其分配给具有
attribute的对象”f”。
7
c.setAttribute("c");将对象的属性更改参考c点它,和它的同一个对象引用f指向它。我希望您现在了解如何将对象作为参数传递给Java :)



