我有invoice
对象,它有两个属性productDescription
,productQuantity
这里是代码:
public class Invoice() implements Cloneable
{
private String productDescription;
private int productQuantity;
//Getters & Setters
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
现在我想在这个类上创建对象的副本,所以我在做
Invoice invoiceCopy = (Invoice)invoice.clone();
现在,如果我更新值invoiceCopy.setProductQuanity = 10
theninvoice
也会更新值,但这不应该发生,有什么建议吗?
更新代码
public class Invoice implements Cloneable {
private String productDescritpion;
private int productQuantity;
public String getProductDescritpion() {
return productDescritpion;
}
public void setProductDescritpion(String productDescritpion) {
this.productDescritpion = productDescritpion;
}
public int getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(int i) {
this.productQuantity = i;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
Invoice invoice = new Invoice();
invoice.setProductQuantity(10);
invoice.setProductDescritpion("nike");
Invoice invoiceCopy = null;
try {
invoiceCopy = (Invoice) invoice.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
invoiceCopy.setProductQuantity(20);
System.out.println("Invoice quantity: " + invoice.getProductQuantity());
System.out.println("InvoiceCopy quantity: "
+ invoiceCopy.getProductQuantity());
}
}