类实现了Cloneable接口,就说明了这个实现类就可以被复制了
对象拷贝时,类的构造函数是不会被执行的,一个实现Cloneable并重写了clone方法的类A,
有一个无参构造或有参构造B,通过new关键字产生了一个对象S,然后在通过S.clone()方式
产生了一个新的对象T,那么在对象拷贝时构造函数B是不会执行的,
深度拷贝与浅度拷贝
浅度拷贝是通过不同的类来获取数据,获取到的数据是不同的类存入的数据
深度拷贝是通过不同的类获取数据,获取的数据是各自类存入的数据
public class Thing implements Cloneable {
// 创建list数组
private ArrayList list = new ArrayList();
public Thing(int aaa) {
System.out.println("无参构造");
}
public Thing clone() {
Thing clone = null;
try {
clone = (Thing) super.clone();
clone.list=(ArrayList)this.list.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return clone;
}
====运行的结果
public static void main(String[] args) {
Thing thing = new Thing(1);
thing.setList("创建对象");
Thing clone = thing.clone();
System.out.println(clone.getList());//[创建对象]
clone.setList("添加数据");
System.out.println("Cloneable获取数据:"+clone.getList());//Cloneable获取数据:[创建对象, 添加数据]
System.out.println("thing获取数据:"+thing.getList());//thing获取数据:[创建对象]
}