首先看下面的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());