参数传递,基本类型是传递值,对象类型通过引用传递
1.1 基本类型传递
byte | short |
---|---|
int | long |
float | double |
boolean | char |
这8中基本类型数据当作参数传递的时候,调用方法后无论方法内做过什么修改,值本身不会被修改。
1.2 对象类型通过引用传递,如下
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");
}
}
-
声明一个名为“ Foo”的名为“ f”的引用,并为其分配一个新的具有属性“ f”的“ Foo”对象。
Foo f = new Foo("f");
-
方法 changeReference,声明了名称为a的类型为Foo的引用,并且最初为其分配了null
public static void changeReference(Foo a)
-
调用方法“ changeReference”时,将为引用“ a”分配对象,该对象作为参数传递。
changeReference(f)
-
声明一个名为Foo类型的b引用,并为其分配一个具有属性b的Foo类型的新对象
Foo b = new Foo("b");
-
“ a = b”对属性为“ b”的对象的引用a进行了新分配,而不是对f进行了分配。
-
调用
modifyReference(Foo c)
方法时,将创建一个引用c
并为该对象分配属性“ f”。
-
c.setAttribute("c");
将更改引用c指向的对象的属性,并且是引用f指向的对象相同的对象。