首先咱們要知道爲何要進行對象克隆,我認爲最大好處就是提升了效率,你想一想用一個對象須要new一次的效率是很是低的。java
這是基本的關於面向對象的問題,涉及到java內存模型。ide
若是一個類包含的屬性都是基本數據類型以及string,integer類型的話,須要用到對象克隆就直接用=就能夠,這些數據類型不涉及到棧內存。this
class Person implements Cloneable{ private int num; private String name; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [num=" + num + ", name=" + name + "]"; } @Override public Person clone(){ Person p = null; try { p = (Person) super.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated cch block e.printStackTrace(); } return p; } } public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Person p = new Person(); p.setNum(1); p.setName("p"); Person pc = p.clone(); pc.setName("pc"); System.out.println(p); System.out.println(pc); } }
這是淺克隆,沒什麼好說的。code
深克隆就是類中包含引用數據類型的,對象
class Person implements Cloneable{ private int num; private String name; private Date date; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "Person [num=" + num + ", name=" + name + ", date=" + date + "]"; } @Override public Person clone(){ Person p = null; try { p = (Person) super.clone(); p.date = (Date) date.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated cch block e.printStackTrace(); } return p; } } public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Person p = new Person(); p.setNum(1); p.setName("p"); p.setDate(new Date()); Person pc = p.clone(); pc.getDate().setTime(12333); pc.setName("pc"); System.out.println(p); System.out.println(pc); } }
若是沒有這一行代碼內存
p.date = (Date) date.clone();
在輸出時會發現對象PC和P的date屬性是一個值,至關於把new date(),從新複製了一遍,而不是指向同一個new date();get