對象引用的問題

 首先看下面的demo1:

  1. int a = new Integer(5);  
  2. int b = a;  
  3. b = b + b;  
  4. System.out.println(a); // 5 as expected  
  5. System.out.println(b); // 10 as expected  

再看demo2:

  1. public class SomeObject { 
  2. public String text; 
  3.  
  4. public SomeObject(String text) { 
  5.     this.setText(text); 
  6.  
  7. public String getText() { 
  8.     return text; 
  9. }    
  10.  
  11. public void setText(String text) { 
  12.     this.text = text; 
  13.  
  14. SomeObject s1 = new SomeObject("first"); 
  15. SomeObject s2 = s1; 
  16. s2.setText("second"); 
  17. System.out.println(s1.getText()); // second as UNexpected 
  18. System.out.println(s2.getText()); // second as expected 

S1爲什麼不是first,二是second,按照上面的邏輯,她應該是first纔對。爲什麼會是這樣呢?

第一個因爲a是基本類型,所以在賦值的時候會把自己copy一份給其他變量,所以執行b=b+b的時候實際是對copy進行操作,所以並不改變原來的a。
第二個是因爲s1,s2,String都是對象類型的。所以在賦值或者傳參的時候都是傳引用的(這裏有不同看法,有人說傳值有人說傳引用,我的理解是java所有都是傳值,但是對象傳的值就是對象的引用)。所以當執行s2=s1的時候就把s1的對象引用賦給了s2,所以對s2的所有操作都會對s1有影響。
如果你希望s1的結果是first,s2的結果是second的話就需要implements Cloneable接口來實現克隆對象。

  1. public class SomeObject implements Cloneable{ 
  2. public String text; 
  3. public SomeObject(String text){ 
  4.     this.setText(text); 
  5. public String getText() { 
  6.     return text; 
  7. public void setText(String text) { 
  8.     this.text = text; 
  9.  
  10. @Override 
  11. protected Object clone(){ 
  12.     SomeObject so=null
  13.     try { 
  14.         so=(SomeObject)super.clone(); 
  15.     } catch (CloneNotSupportedException e) { 
  16.         e.printStackTrace(); 
  17.     } 
  18.     return so; 

然後在使用的時候變成:

  1. public class Test { 
  2. public static void main(String[] args) { 
  3.     SomeObject s1 = new SomeObject("first");  
  4.     SomeObject s2 = (SomeObject) s1.clone();  
  5.     s2.setText("second");  
  6.     System.out.println(s1.getText());   
  7.     System.out.println(s2.getText()); 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章