在编程时如果已经存在对象A,若想要得到一个与A完全相同的对象B,并在此后对B进行修改不会对A产生影响,则可以使用克隆。简单的赋值语句创建的只是对象的引用,无法满足这种要求。克隆分为深拷贝与浅拷贝。
克隆需要实现Cloneable接口,Cloneable接口是Java提供的少数标记接口之一。标记接口不包含任何方法,唯一的作用是允许在类型查询中使用instanceof。
Object类中的clone()方法声明为protected,所以代码不能直接调用,需要先继承Object类,但是由于java中的类都是默认继承Object,所有这点也不用关心。要实现克隆需要重写clone()方法,在方法中需要修改clone()的修饰符为public,方便其他类调用。
1.如果对象包含子对象的引用,在克隆之后拷贝对象与原对象都包含子对象的引用,也就是对A中的子对象的修改会造成B中子对象的修改,则称为浅拷贝。
public class Shallow {
public static void main(String[] args) throws CloneNotSupportedException {
Son son = new Son("小张三", 3);
Father father = new Father("张三", 30, son);
Father clonedFather = father.clone();
father.son.setName("小小小张三");
System.out.println("father的儿子:" + father.son);
System.out.println("clonedFather的儿子:" + clonedFather.son);
}
}
class Father implements Cloneable{
public String name;
public int age;
public Son son;
public void setSon(Son son) {
this.son = son;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public Father(String name, int age, Son son) {
this.name = name;
this.age = age;
this.son = son;
}
public Father clone() throws CloneNotSupportedException {
return (Father) super.clone();
}
}
class Son {
public String name;
public int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public Son(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Son{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
结果:
2.如果对象包含子对象的引用,在克隆之后拷贝对象与原对象都包含子对象的引用,但是对A中的子对象的修改不会造成B中的子对象的修改,则称之为深拷贝。若对A克隆得到B,A的子对象为C,实现深拷贝需要:
1.在A中重写clone方法,并在方法中实现克隆子对象C.
2.若C是自己写的类,需要重写clone()方法。return ( C ) super.clone();
public class Deep {
public static void main(String[] args) throws CloneNotSupportedException {
Son son = new Son("小张三", 3);
Father father = new Father("张三", 30, son);
Father clonedFather = father.clone();
father.son.setName("小小小张三");
System.out.println("father的儿子:" + father.son);
System.out.println("clonedFather的儿子:" + clonedFather.son);
}
}
class Father implements Cloneable{
public String name;
public int age;
public Son son;
public void setSon(Son son) {
this.son = son;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public Father(String name, int age, Son son) {
this.name = name;
this.age = age;
this.son = son;
}
public Father clone() throws CloneNotSupportedException {
Father cloned = (Father) super.clone();
cloned.son = son.clone();
return cloned;
}
}
class Son implements Cloneable{
public String name;
public int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public Son(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Son{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Son clone() throws CloneNotSupportedException {
return (Son) super.clone();
}
}
结果: