Java引用傳遞&值傳遞

當一個對象被當作參數傳遞到一個方法後,此方法可改變這個對象的屬性,並可返回變化後的結果,那麼這裏到底是值傳遞還是引用傳遞? 
    答:是值傳遞。Java 編程語言只有值傳遞參數。當一個對象實例作爲一個參數被傳遞到方法中時,參數的值就是該對象的引用一個副本。指向同一個對象,對象的內容可以在被調用的方法中改變,但對象的引用(不是引用的副本)是永遠不會改變的。


Java參數,不管是原始類型還是引用類型,傳遞的都是副本(有另外一種說法是傳值,但是說傳副本更好理解吧,傳值通常是相對傳址而言)。

    如果參數類型是原始類型,那麼傳過來的就是這個參數的一個副本,也就是這個原始參數的值,這個跟之前所談的傳值是一樣的。如果在函數中改變了副本的 值不會改變原始的值.
    如果參數類型是引用類型,那麼傳過來的就是這個引用參數的副本,這個副本存放的是參數的地址。如果在函數中沒有改變這個副本的地址,而是改變了地址中的 值,那麼在函數內的改變會影響到傳入的參數。如果在函數中改變了副本的地址,如new一個,那麼副本就指向了一個新的地址,此時傳入的參數還是指向原來的 地址,所以不會改變參數的值。

例:
複製代碼
 1 public class ParamTest {
 2     public static void main(String[] args){
 3           /**
 4            * Test 1: 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            * Test 2: 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            * Test 3: Methods can't attach new objects to object parameters
23            */
24           System.out.println("\nTesting swap:");
25           Employee a = new Employee("Alice", 70000);
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     private static void swap(Employee x, Employee y) {
35         Employee temp = x;
36         x=y;
37         y=temp;
38         System.out.println("End of method: x=" + x.getName());
39         System.out.println("End of method: y=" + y.getName());
40     }
41 
42     private static void tripleSalary(Employee x) {
43         x.raiseSalary(200);
44         System.out.println("End of method: salary=" + x.getSalary());
45     }
46 
47     private static void tripleValue(double x) {
48         x=3*x;
49         System.out.println("End of Method X= "+x);
50     }
51 }
複製代碼

  顯示結果:

複製代碼
Testing tripleValue:
Before: percent=10.0
End of Method X= 30.0
After: percent=10.0

Testing tripleSalary:
Before: salary=50000.0
End of method: salary=150000.0
After: salary=150000.0

Testing swap:
Before: a=Alice
Before: b=Bob
End of method: x=Bob  //可見引用的副本進行了交換
End of method: y=Alice
After: a=Alice  //引用本身沒有交換
After: b=Bob
複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章