实现克隆的方法步骤:
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 * */}