浅克隆: 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
深克隆:深复制把要复制的对象所引用的对象都复制了一遍。下面用一个例子来看一下:
public class Point implements Cloneable {
private int x;
private int y;
public Point(){}
public Point(int x,int y){
this.x=x;
this.y=y;
}
public void setX(int x){this.x=x;}
public void setY(int y){this.y=y;}
public int getX(){return x;}
public int gety(){return y;}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
/**
* @param args
*/
public static void main(String[] args) throws CloneNotSupportedException{
// TODO 自动生成方法存根
Table table=new Table();
table.setCenter(new Point(2,3));
Point yuanshi=table.getCenter();
Table clontable=(Table)table.clone();
Point cloncenter=clontable.getCenter();
cloncenter.setX(4);
cloncenter.setY(21);
System.out.print(cloncenter.getX());
System.out.print(yuanshi.getX());
}
}
以上定义了可以克隆的类,以及在main函数中进行的测试。下面的类是关键所在:
public class Table implements Cloneable{
private Point center;
public void setCenter(Point center){
this.center=center;
}
public Point getCenter(){
return center;
}
public Object clone() throws CloneNotSupportedException{
Table table=(Table) super.clone();
if (this.center!=null){
table.center=(Point)center.clone();
}
return table;
}
}
Table类中,如果将红色代码去掉,就属于浅克隆,加上就是深克隆,可以将对象复制出来,两个对象在操作的过程中不会相互影响。
去掉红色代码输出结果是:4 4
加上后输出结果是:4 2