Cloneの簡単使用


public class Employee implements Cloneable{
private float salary;
private String name;
private Date hireDay;
/**
 *     :            ,                 ,             ,
 *            ,                  ,                 
 * 
 *     :        ,           :     A,     A           ,          A       B,
 *      B          A   ,    ,A B        , B      A     。 Java   ,
 *                   。              ,   clone()        ,        
 * 
 *       :
 * 1、http://blog.csdn.net/shootyou/article/details/3945221
 * 2、http://blog.csdn.net/it_man/article/details/1404550
 * 3、http://blog.csdn.net/naivesoft/article/details/6774550   【java   String    】
 * 
 *             :
 *   Object  clone()        :                   ,              。       ,           ,
 *          ,                 ,    clone                             。
 * 
 *  :             String  ,  String        ,              
 */
/**
 * 
 * @param args
 * @throws CloneNotSupportedException      Cloneable  ,           
 */
public static void main(String[] args) throws CloneNotSupportedException {
	Employee e=new Employee(3000.0f,"xw",new Date());
	/*    (Shallow Clone)
	 * Object        Clone         ,             copy
	 *        hireDay         ,    reference  ,  Clone          Date   
	 * reference,                Date  ,                  
	 */
	Employee e1=(Employee)e.clone();
	System.out.println(e1.hashCode()+":"+e.hashCode());//        ,hashcode   
	e1.salary=200;
	e1.name="hj";
	e1.hireDay.setDate(9);
	System.out.println(e.salary+"#"+e1.salary);//3000.0#200.0
	System.out.println(e.name+"#"+e1.name);	   //xw#hj  ??           ,         name   
	System.out.println(e.hireDay.getDate()+"#"+e1.hireDay.getDate());//9#9  
	//      ,           
	//      clone         7#9
	
}

public Employee(float salary,String name,Date hireDay){
	this.salary=salary;
	this.name=name;
	this.hireDay=hireDay;
}

@Override
/*
 *                          ,       (deep Clone)
 *     Clone  ,                 
 */
protected Object clone() throws CloneNotSupportedException {
	Employee clone=(Employee)super.clone();// e       ,         
	clone.hireDay=(Date)hireDay.clone();//          ,                
	//      hireDay       hireDay,                      
	return clone;
}
}
/**
      :
  14576877:12677476
  3000.0#200.0
  xw#hj
  24#9
 */