8月22日完成 listing 6-2的练习

从此将深刻理解shallow clone和 deep clone的区别。


----

package jc8;


import java.util.*;




/**
 *listing 6-2
 * 这段代码用于演示deepclone和shallowclone。
 * clone能够把变量指向的对象另外复制一份,但如果对象中还包含*对象*,则还要将*对象*clone一遍
 * 以达到clone的目的。clone的目的是便于操纵clone,而不影响original对象的值
 * @author Administrator
 *
 */
public class Demon implements Cloneable{


private int bullets;
private String name;
Date bornDate;

public Demon(String aName,int aBullets){
name=aName;
bullets=aBullets;
bornDate=new Date();//GregorianCalendar().getTime();
}


public String getName(){
return name;
}

public int getBullets(){
return bullets;
}

public void setBullets(int aBullets){
bullets=aBullets;
}

public String  toString(){
return getClass()+", name:"+name+", bullets:"+bullets+", bornDate"+bornDate;
}


public Demon clone(){
try {
//Object clone, the so called shallow clone
Demon otherDemon=(Demon)super.clone();
//deep clone. if not, the original's bornDate will also be Sun Mar 21 00:00:00 CST 2010
//but we deep cloned, so the original's bornDate is still in year 2003.
otherDemon.bornDate=(Date)bornDate.clone();//
return otherDemon;
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}


public void setBornDate(int year,int month,int day){
//为什么不使用下面的这段代码进行deep clone的演示?
//bornDate=new GregorianCalendar(year,month-1,day).getTime();
//如果果真如上,则无需deepclone,因为上面的new其实已经创建了另外一个新的对象实例
//这个新的对象实例实际上是独立于original的bornDate的。
//也就是说,second.bornDate将指向的是一个新的Date对象,不会对orignal.bornDate产生啥影响了。

Date newBornDate=new GregorianCalendar(year,month-1,day).getTime();
bornDate.setTime(newBornDate.getTime());
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值