共享heap中的空间
实现clone()方法条件:
clone()为浅拷贝,若想改为深拷贝,需类中可变域生成新的实例
//浅拷贝:
public class ShallowCopy implements Cloneable{ private Date begin; public Date getBegin(){return this.begin;} public void setBegin(Date d){this.begin=d;} public Object clone(){ Object obj=null; try { obj=super.clone(); }catch (CloneNotSupportedException ex) { ex.printStackTrace(); } return obj; } }
//深拷贝:
public class DeepCopy implements Cloneable{ private Date begin; public Date getBegin(){return this.begin;} public void setBegin(Date d){this.begin=d;} public Object clone(){ DeepCopy obj=null; try{ obj=(DeepCopy)super.clone(); }catch (CloneNotSupportedException ex) { ex.printStackTrace(); } obj.setBegin((Date)this.getBegin().clone()); return obj; } }