package test1; import java.util.Date; import java.util.GregorianCalendar; public class CloneTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { Employee original = new Employee("john Q. Public",5000); original.setHireDay(2000, 1, 1); Employee copy = original.clone(); copy.raiseSalary(10); copy.setHireDay(2002, 12, 31); System.out.println("original=" + original); System.out.println("copy=" + copy); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } class Employee implements Cloneable{ private String name; private double salary; private Date hireDay; public Employee(String n,double s){ name = n; salary = s; hireDay = new Date(); } public Employee clone() throws CloneNotSupportedException{ Employee cloned = (Employee) super.clone(); cloned.hireDay = (Date) hireDay.clone(); return cloned; } public void setHireDay(int year,int month,int day){ Date newHireDay = new GregorianCalendar(year,month-1,day).getTime(); hireDay.setTime(newHireDay.getTime()); } public void raiseSalary(double byPercent){ double raise = salary * byPercent /100; salary += raise; } public String toString(){ return "Employee[name="+name+",salary="+salary+",hireDay="+hireDay+"]"; } }
输出结果:
original=Employee[name=john Q. Public,salary=5000.0,hireDay=Sat Jan 01 00:00:00 CST 2000]
copy=Employee[name=john Q. Public,salary=5500.0,hireDay=Tue Dec 31 00:00:00 CST 2002]
学习小结:
在对各个域进行对应的拷贝时,如果对象中包含了子对象的引用,拷贝的结果会是的两个域引用同一个子对象
因此原始对象与拷贝对象共享这部分信息。若这部分信息不会发生改变时,则进行浅拷贝(默认拷贝)即可,但是
如果这部分信息会发生改变,那么需要进行深拷贝,以防止一个对象对这部分信息的修改影响了另一个对象。
拷贝时:
1.实现Cloneable接口
2.使用public访问修饰符重新定义clone方法
3.实现深拷贝的时候必须克隆所有可变域的实例域(如上代码中的hireDay域)
java clone方法
最新推荐文章于 2023-02-09 20:39:12 发布