1、通识性问题说明:
(1)String类不可被clone(String不可修改)
(2)Clone对应的异常:CloneNotSupportedException
2、克隆的自定义实现 : 实现Cloneable接口的类需要重写clone方法
public class CloneTest {
public static void main(String[] args) {
Circle circle = new Circle();
Circle circle2 = (Circle) circle.clone();
System.out.println(circle);
System.out.println(circle2);
}
}
/*自定义实现clone*/
class Circle implements Cloneable{
private double radius = 1.0;
public final double PI = 3.14;
@Override
protected Object clone() throws CloneNotSupportedException {
try {
return super.clone();
}catch (CloneNotSupportedException e){
return null;
}
}
}
运行后发现,通过克隆得到了新的Circle对象
3、浅拷贝:
public class TVTest {
public static void main(String[] args) throws CloneNotSupportedException {
TV a = new TV();
TV b = (TV) a.clone();
}
}
class TV implements Cloneable{
private boolean on;
private Date buyDate = new Date();
@Override
protected Object clone() throws CloneNotSupportedException {
try {
return super.clone();
}catch (CloneNotSupportedException e){
return null;
}
}
}
4、深拷贝:
import java.util.Date;
public class TVTest {
public static void main(String[] args) throws CloneNotSupportedException {
TV a = new TV();
TV b = (TV) a.clone();
}
}
class TV implements Cloneable{
private boolean on;
private Date buyDate = new Date();
@Override
protected Object clone() throws CloneNotSupportedException {
try {
TV temTV = (TV) super.clone();
temTV.buyDate = (Date) buyDate .clone();
return temTV;
}catch (CloneNotSupportedException e){
return null;
}
}
}
写代码时最好是用深拷贝,因为这样不至于在改了一个公共引用对象后,产生数据矛盾,把不该改的地方也改了。