1. 咱們知道在程序設計語言中,將參數傳遞分爲按值調用和按引用調用。c++
按值調用:表示方法接收的是調用者提供的值。而按引用調用表示方法接收的是調用者提供的變量地址。
一個方法能夠修改傳遞引用所對應的變量值,而不能修改傳遞值調用所對應的變量值。函數
咱們在c++中知道判斷最好的方法就是寫一個swap函數,根據結果看就能判斷是按值調用仍是按引用調用。this
class Student { private float score; } public class ParamTest { public static void main(String[] args) { Student x = new Student(0); Student y = new Student(100); System.out.println("交換前:"); System.out.println("x的分數:" + x.getScore() + "--- y的分數:" + y.getScore()); swap(x, y); System.out.println("交換後:"); System.out.println("x的分數:" + x.getScore() + "--- y的分數:" + y.getScore()); } public static void swap(Student a, Student b) { Student temp = a; a= b; b= temp; } }
運行結果:spa
交換前: a的分數:0.0--- b的分數:100.0 交換後: a的分數:0.0--- b的分數:100.0
能夠看出,二者並無實現交換。從這個過程當中能夠看出,Java對對象採用的不是引用調用,實際上,對象引用進行的是值傳遞。設計
2. 要想實現數值變換,咱們能夠寫函數來實現:code
class Student { private float score; public Student(float score) { this.score = score; } public void setScore(float score) { this.score = score; } public float getScore() { return score; } } public class ParamTest { public static void main(String[] args) { Student stu = new Student(80); raiseScore(stu); System.out.print(stu.getScore()); } public static void raiseScore(Student s) { s.setScore(s.getScore() + 10); } }
3. 總結一下Java老是採用按值調用。方法獲得的是全部參數值的一個拷貝,特別的,方法不能修改傳遞給它的任何參數變量的內容。方法參數共有兩種類型:基本數據類型和對象引用對象