Java方法參數的傳遞方式
阿新 • • 發佈:2018-09-12
amt 設計 urn hang wid pan 核心技術 objects height
程序設計語言中,將參數傳遞給方法(或函數)有兩種方法。按值傳遞(call by value)表示方法接受的是調用者提供的值;按引用調用(call by reference)表示方法接受的是調用者提供的變量地址。Java程序設計語言都是采用按值傳遞。下面通過例題進行說明:
1 public class ParamTest { 2 public static void main(String[] args) { 3 /* 4 *Test1: Methods can‘t modify numeric parameters 5 */ 6 System.out.println("Testing tripleValue:"); 7 double percent = 10; 8 System.out.println("Before: percent=" + percent); 9 tripleValue(percent); 10 System.out.println("After: percent=" + percent); 11 12 /* 13 *Test2: Methods can change the state of object parameters 14 */ 15 System.out.println("\nTesting tripleSalary"); 16 Employee harry = new Employee("Harry", 50000); 17 System.out.println("Before: salary=" + harry.getSalary()); 18 tripleSalary(harry); 19 System.out.println("After: salary=" + harry.getSalary()); 20 21 /* 22 *Test3: Methods can‘t attach new objects to object parameters 23 */ 24 System.out.println("\nTesting swap"); 25 Employee a = new Employee("Alice", 30000); 26 Employee b = new Employee("Bob", 60000); 27 System.out.println("Before: a=" + a.getName()); 28 System.out.println("Before: b=" + b.getName()); 29 swap(a, b); 30 System.out.println("After: a=" + a.getName()); 31 System.out.println("After: b=" + b.getName()); 32 } 33 34 public static void tripleValue(double x) { 35 x *= 3; 36 System.out.println("End of method: x=" + x); 37 } 38 39 public static void tripleSalary(Employee x) { 40 x.raiseSalary(200); 41 System.out.println("End of method: salary=" + x.getSalary()); 42 } 43 44 public static void swap(Employee x, Employee y) { 45 Employee temp = x; 46 x = y; 47 y = temp; 48 System.out.println("End of method: x=" + x.getName()); 49 System.out.println("End of method: y=" + y.getName()); 50 } 51 } 52 53 class Employee { 54 private String name; 55 private double salary; 56 public Employee(){} 57 public Employee(String name, double salary){ 58 this.name = name; 59 this.salary = salary; 60 } 61 62 public String getName() { 63 return name; 64 } 65 66 public double getSalary() { 67 return salary; 68 } 69 70 public void raiseSalary(double byPercent){ 71 double raise = salary * byPercent / 100; 72 salary += raise; 73 } 74 }
程序運行結果為:
從以上例題可以總結Java中方法參數的使用情況:
- 一個方法不能修改一個基本數據類型的參數(即數值型或布爾型)。
- 一個方法可以改變一個對象(數組)參數的狀態。
- 一個方法不能讓對象參數(數組)引用一個新的對象。
以上內容均參考:java核心技術 卷1 第十版 4.5節
———————————————————————————————————————————
下面通過畫內存圖說明參數傳遞過程:
基本數據類型的傳遞:
- percent將值拷貝給x,percent與x的地址值不同;
- tripleValue()方法將x的值10乘以3後得到10,percent的值不變;
- tripleValue()彈棧後,參數變量x不再使用。
對象或數組作為參數傳遞:
- Employee harry = new Employee("Harry", 50000); 創建了一個對象變量harry,引用了Employee的一個對象;
- tripleSalary(harry); 將對象harry的地址值傳遞給參數x, 此時變量harry和x都引用了堆中的同一個Employee對象;並通過方法將這一對象的薪金提高了200%;
- tripleSalary(harry)方法彈棧後,參數變量x不再使用。對象變量harry繼續引用那個薪金增至3倍的對象。
Java方法參數的傳遞方式