Father
package com.kevin.test.test; /** * Created by jinyugai on 2018/11/16. */ public class Father implements Cloneable { public String xm; public Child child; public Girl girl; public Father(Child child,Girl girl) { this.child = child; this.girl = girl; } @Override protected Object clone() throws CloneNotSupportedException { Father father = (Father)super.clone(); father.girl = (Girl)girl.clone(); return father; } }
Child
package com.kevin.test.test;
/**
* Created by jinyugai on 2018/11/16.
*/
public final class Child {
public String name;
}
Girl
package com.kevin.test.test; /** * Created by jinyugai on 2018/11/16. */ public class Girl implements Cloneable { public String name; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
测试
package com.kevin.test.test;
/**
* Created by jinyugai on 2018/11/16.
*/
public class CloneTest {
public static void main(String[] args) {
Father father1 = new Father(new Child(),new Girl());
father1.xm = "Kevin";
father1.child.name = "youyou";
father1.girl.name = "toto";
try {
//浅拷贝
// child类虽然声明为final修饰,但是child并没有被重新new 没有重新划分内存
//深拷貝
// girl类深拷贝
Father father2 = (Father)father1.clone();
father2.xm = "kevin2";
father2.child.name = "youyou2";
father1.girl.name = "toto2";
System.out.println("打印fathe ===========");
System.out.println("打印fathe1 :"+father1.xm);
System.out.println("打印fathe2 :" + father2.xm);
System.out.println("打印child.name ===========");
System.out.println("打印fathe1 child.name:"+father1.child.name);
System.out.println("打印fathe2 child.name:"+father2.child.name);
System.out.println("打印girl.name ===========");
System.out.println("打印fathe1 girl.name:"+father1.girl.name);
System.out.println("打印fathe2 girl.name:"+father2.girl.name);
System.out.println("对比是否指向同一个引用 ===========");
System.out.println(father1.xm == father2.xm);
System.out.println(father1.child == father2.child);
System.out.println(father1.girl == father2.girl);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
结果--浅拷贝--直接复制的是属性对象的地址 ,没有new一个新的
打印fathe ===========
打印fathe1 :Kevin
打印fathe2 :kevin2
打印child.name ===========
打印fathe1 child.name:youyou2
打印fathe2 child.name:youyou2
打印girl.name ===========
打印fathe1 girl.name:toto2
打印fathe2 girl.name:toto
对比是否指向同一个引用 ===========
false
true
false
深拷贝--如果想要深拷贝一个对象, 这个对象必须要实现Cloneable接口,实现clone方法,并且在clone方法内部,把该对象引用的其他对象也要clone一份 , 这就要求这个被引用的对象必须也要实现Cloneable接口并且实现clone方法。