public class Rectangle implements Cloneable {
double width;
double height;
Date dateCreated;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Rectangle(double width, double height, Date dateCreated){
this.width = width;
this.height = height;
this.dateCreated = dateCreated;
}
public double getArea(){
return width * height;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
}
public class Test {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(2,1, new Date());
Rectangle rectangle1 = null;
try {
rectangle1 = (Rectangle) rectangle.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
rectangle.setDateCreated(new Date(1));
System.out.println(rectangle1.getDateCreated());
System.out.println(rectangle.getDateCreated());
}
}
在上面的代码中,由于clone()方法创建浅表副本,因此我希望非原始类型具有相同的引用。那么,为什么在对象矩形中更改dateCreated字段的内容却在矩形1字段中更改同一字段呢?
答案 0 :(得分:2)
您的clone
方法没有执行任何操作。您需要实现它。
即使实现了clone
方法,您仍然会遇到问题中描述的问题。您没有更改Date
对象的值,而是将其替换为新的Date
对象。这对原始Date
对象(至今仍被rectangle1
引用)没有影响。