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 modify 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"); }}我将逐步解释这一点:
- 声明一个名为ftype 的引用,Foo并将其分配给Foo具有属性的type的新对象”f”。
Foo f = new Foo("f");- 从方法方面,声明Foo具有名称的类型引用,a并将其初始分配给null。
public static void changeReference(Foo a)
- 调用方法时changeReference,引用a将分配给作为参数传递的对象。
changeReference(f);
- 声明一个名为btype 的引用,Foo并将其分配给Foo具有属性的type的新对象”b”。
Foo b = new Foo("b");a = b
正在将引用aNOT 分配给f属性为的对象"b"
。在调用
modifyReference(Foo c)method
时,将c创建一个引用并将其分配给具有attribute的对象”f”。c.setAttribute("c");将更改引用所c指向的对象的属性,并且引用所指向的对象是同一对象f。
我希望你现在了解如何将对象作为参数传递给Java :)



