Java之Clone()

实现克隆的方法步骤:
1.实现Cloneable接口;
2.重载Object类中的Clone方法,定义为public;
3.在重载中,调用super.clone()方法;(浅克隆)
4.成员变量中有对象类型时,要对对象分别调用.clone()方法。(深克隆)
package com.selfCode;
import java.util.Date;

/**
 * 练习Clone
 *
 * @author delia
 * @create 2016-05-12 上午9:52
 */

public class CloneTest implements Cloneable{
    private Date date = new Date();
    private StringBuffer sb = new StringBuffer("sssss");
    private String s = "abc";

    public StringBuffer getSB(){
        return sb;
    }
    public Date getDate(){
        return date;
    }

    public void change(){
        this.date.setMonth(5);
        s += "ddddd";//s这是因为String被 Sun公司的工程师写成了一个不可更改的类(immutable class),在所有String类中的函数都不能更改自身的值。
        sb.append("eeeeeeee");
    }
    public void show(){
        System.out.println("Date:"+date);
        System.out.println("String:"+s);
        System.out.println("StringBuffer:"+sb.toString());
    }
    public Object clone(){
        CloneTest o = null;
        try {
            o = (CloneTest) super.clone();//浅克隆,基本类型变量
        }catch (Exception e){
            e.printStackTrace();
        }
        o.date = (Date)this.getDate().clone();//浅克隆,对象类型变量
        o.sb = new StringBuffer(this.getSB().toString());//不是所有的类都能实现深度clone的,StringBuffer没有重载clone()方法,更为严重的是StringBuffer还是一个 final类,这也是说我们也不能用继承的办法间接实现StringBuffer的clone。
        return o;
    }

    public static void main(String[] args) {
        CloneTest a = new CloneTest();
        CloneTest b = (CloneTest) a.clone();
        b.change();
        System.out.println(a.toString());
        System.out.println(b.toString());
        a.show();
        b.show();
    }
/*执行结果:
com.selfCode.CloneTest@6d3552ed
com.selfCode.CloneTest@47d77d9e
Date:Thu May 12 10:44:11 CST 2016
String:abc
StringBuffer:sssss
Date:Sun Jun 12 10:44:11 CST 2016
String:abcddddd
StringBuffer:ssssseeeeeeee
* */

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值