如何实现Cloneable接口?

 

在Java中,如果用赋值运算符将一个对象赋值给另一个,只有这个对象的引用会被拷贝,所以改变其中一个对象会对另一个对象产生影响。
Java使用Object的clone()方法来拷贝一个对象的内容到另一个对象,当一个需要拷贝的对象包含其他对象的引用时就会出现问题。
可以实现Cloneable接口来重载Object类的clone方法。

下面这个例子就是展示如何实现cloneable接口的:

public class CloneExp implements Cloneable {

private String name;
private String address;
private int age;
private Department depart;
public CloneExp(){

}
public CloneExp(String aName, int aAge, Department aDepart) {

this.name = aName;
this.age = aAge;
this.depart = aDepart;
}

protected Object clone() throws CloneNotSupportedException {

CloneExp clone=(CloneExp)super.clone();

// 执行Department的一个浅拷贝
clone.depart=(Department)depart.clone();
return clone;

}
public static void main(String[] args) {

CloneExp ce=new CloneExp();

try {
// 执行CloneExp的深拷贝
CloneExp cloned=(CloneExp)ce.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}

}
}
posted @ 2015-06-06 19:18  hephec  阅读(341)  评论(0编辑  收藏  举报