首頁 > Java > java教程 > 主體

Java值傳遞與引用傳遞詳解

高洛峰
發布: 2017-01-24 16:54:00
原創
1459 人瀏覽過

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

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

如果參數類型是原始型,那麼傳過來的就是這個參數的一個副本,也就是這個原始參數的值,這個跟之前所談的傳值是一樣的。如果在函數中改變了副本的值不會改變原始的值。

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

例:

public class ParamTest {
  public static void main(String[] args){
   /**
    * Test 1: Methods can't modify numeric parameters
    */
   System.out.println("Testing tripleValue:");
   double percent = 10;
   System.out.println("Before: percent=" + percent);
   tripleValue(percent);
   System.out.println("After: percent=" + percent);
  
   /**
   * Test 2: Methods can change the state of object parameters
   */
   System.out.println("\nTesting tripleSalary:");
   Employee harry = new Employee("Harry", 50000);
   System.out.println("Before: salary=" + harry.getSalary());
   tripleSalary(harry);
   System.out.println("After: salary=" + harry.getSalary());
  
   /**
   * Test 3: Methods can't attach new objects to object parameters
   */
   System.out.println("\nTesting swap:");
   Employee a = new Employee("Alice", 70000);
   Employee b = new Employee("Bob", 60000);
   System.out.println("Before: a=" + a.getName());
   System.out.println("Before: b=" + b.getName());
   swap(a, b);
   System.out.println("After: a=" + a.getName());
   System.out.println("After: b=" + b.getName());
  }
  
  private static void swap(Employee x, Employee y) {
   Employee temp = x;
   x=y;
   y=temp;
   System.out.println("End of method: x=" + x.getName());
   System.out.println("End of method: y=" + y.getName());
  }
  
  private static void tripleSalary(Employee x) {
   x.raiseSalary(200);
   System.out.println("End of method: salary=" + x.getSalary());
  }
  
  private static void tripleValue(double x) {
   x=3*x;
   System.out.println("End of Method X= "+x);
  }
 }
登入後複製

顯示結果:

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
登入後複製

   

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多PHP中文網。

更多Java值傳遞與引用傳遞詳解相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!