Java 的方法參數只有按值傳遞。方法接收到的始終是調用者提供值的複本。基本類型複製的是數值本身,對象參數複製的是對象引用的副本。
public class ParamTest {
public static void main(String[] args) {
int price = 5;
doubleValue(price);
System.out.println(price);
}
public static void doubleValue(int x) {
x = 2 * x;
}
}
輸出結果仍然是 5。因為 x 只是 price 的副本,方法內部修改 x,不會影響外部的 price。
如果參數是對象,方法拿到的是引用的副本。副本與原引用指向同一個對象,因此可以改變對象內部狀態。
public class ParamTest {
public static void main(String[] args) {
Student stu = new Student(80);
raiseScore(stu);
System.out.println(stu.getScore());
}
public static void raiseScore(Student s) {
s.setScore(s.getScore() + 10);
}
}
輸出 90.0。stu 與 s 指向同一個 Student 對象,所以對象的分數被改變。
public static void swap(Student x, Student y) {
Student temp = x;
x = y;
y = temp;
}
交換的只是方法內部的引用副本,外部的 a 與 b 仍然指向原對象,因此不會發生交換。