1对象的克隆(clone)
单纯的同类的两个对象a0 a00,a0=a00只是栈指向同一个堆,而不是开辟两个新堆,修改其中一个,另一个也会受牵连。
需要重写Clone()方法,并且实现Cloneable接口。
浅层克隆:仅仅对对象成员的逐成员克隆
package homework.B1.src.com.C12; /** * Created by Administrator on 2018/2/27 0027. * 作业:浅层克隆: */ public class A { public static void main(String[] args) { A0 a0=new A0(); a0.setI(2); try { A0 a00=(A0)a0.clone(); System.out.println(a00.getI()); a0.setI(3); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } class A0 implements Cloneable{ private int i; private String s; public A0(int i, String s) { this.i = i; this.s = s; } public A0() { } public int getI() { return i; } public void setI(int i) { this.i = i; } public String getS() { return s; } public void setS(String s) { this.s = s; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
深层克隆:不仅拷贝对象的字段,而且还对对象通过字段关联的其他对象实施拷贝,即对于当前对象关联的其他对象,深克隆要先创建这个其他对象再实施克隆,迭代。
package homework.B1.src.com.C12; /** * Created by Administrator on 2018/2/7 0027. * 深克隆 */ public class B { public static void main(String[] args) { Cat c=new Cat(); Cat c1; c.setAnimal(new Animal()); c.getAnimal().setName("asd"); try { c1=(Cat)c.clone(); c.getAnimal().setName("zxc"); System.out.println(c1.getAnimal().getName()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } class Cat implements Cloneable{ private Animal animal; private String name; private int age; @Override protected Object clone() throws CloneNotSupportedException { Animal animal1=(Animal)this.animal.clone(); Cat cat1=(Cat)super.clone(); cat1.setAnimal(animal1); return cat1; } public Cat() { } public Cat(Animal animal, String name, int age) { this.animal = animal; this.name = name; this.age = age; } public Animal getAnimal() { return animal; } public void setAnimal(Animal animal) { this.animal = animal; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Animal implements Cloneable{ private String name; public Animal(String name) { this.name = name; } public Animal() { } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
应用:有些对象创建复杂,因此使用clone来进行对象创建,实现了原型模式;