有時候建立對象是須要耗費不少資源,可是每一個對象之間又有大量的重複。咱們能夠選擇在建立好一個對象後,以之做爲模板克隆出其餘對象,稍做修改,便可用於其餘地方。this
須要實現Cloneable接口,重寫clone()方法。其實就是調用的Object類的clone()方法。spa
克隆對象只是複製了原對象的數據,每一個對象仍是獨立的,他們的內存地址不一樣。code
/** * Created by wangbin10 on 2018/5/18. */ public class Prototype2 implements Cloneable,Serializable { private static final long serialVersionUID = 2L; private String name; private Integer payAmount; private String msg; public Prototype2() { } public Prototype2(String name, Integer payAmount, String msg) { this.name = name; this.payAmount = payAmount; this.msg = msg; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPayAmount() { return payAmount; } public void setPayAmount(Integer payAmount) { this.payAmount = payAmount; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Prototype2 clone() throws CloneNotSupportedException { Prototype2 clone = (Prototype2) super.clone(); return clone; } }
/** * Created by wangbin10 on 2018/5/18. */ public class PTest { public static void main(String[] args) throws CloneNotSupportedException { Prototype2 p1=new Prototype2("zhangsan",23,"hello!welcome to beijing!"); System.out.println(p1.getName()+p1.getPayAmount()+p1.getMsg()); Prototype2 p2 = p1.clone(); p2.setName("lisi"); p2.setPayAmount(24); System.out.println(p2.getName()+p2.getPayAmount()+p2.getMsg()); System.out.println("============================"); System.out.println(p1.getName()+p1.getPayAmount()+p1.getMsg()); } }