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字段中的同一字段?
最佳答案
您的clone
方法不执行任何操作。您需要实现它。
即使实现了clone
方法,您仍然会遇到问题中描述的问题。您没有更改Date
对象的值,而是将其替换为新的Date
对象。这对原始的Date
对象没有影响,该对象仍被rectangle1
引用。