Java浅拷贝

时间:2019-07-14 21:11:57

标签: java

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字段中更改同一字段呢?

1 个答案:

答案 0 :(得分:2)

  1. 您的clone方法没有执行任何操作。您需要实现它。

  2. 即使实现了clone方法,您仍然会遇到问题中描述的问题。您没有更改Date对象的值,而是将其替换为新的Date对象。这对原始Date对象(至今仍被rectangle1引用)没有影响。