浅拷贝:
ABC a = new ABC();
ABC b = a;
如果在对象b中把某个域值改了,那么对象a对应的域值也会跟着变化
深拷贝:
把b改了,a保持原样
不管浅、深拷贝都要实现Cloneable接口,然后重写父类的clone方法(如果类中只有基本数据类型[包括String],不用重写该方法也可以)
如果ABC类中只有基本数据类型域(包括String):
public class testClone implements Cloneable{
String name;
int id;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
testClone a = new testClone();
a.id = 1;
a.name = "jason";
testClone o = (testClone)a.clone();
o.id = 100;
System.out.println(o.id);
System.out.println(a.id);
}
}
如果ABC类中存在引用类型域:
public class testClone implements Cloneable{
String name;
int id;
int[] arr = new int[2];
@Override
protected Object clone() throws CloneNotSupportedException {
testClone clone = (testClone)super.clone();//向下转型
clone.arr = arr.clone();//拷贝一个arr数组(多分配一小块内存),然后让上面的clone对象的arr域指向该内存地址即可
return clone;
}
public static void main(String[] args) throws CloneNotSupportedException {
testClone a = new testClone();
a.id = 1;
a.name = "jason";
a.arr[0] = 911;
testClone o = (testClone)a.clone();
o.arr[0] = 110;
System.out.println(o.arr[0]);
System.out.println(a.arr[0]);
}
}