Search code examples
javaclone

Java : Issue with Object Cloning?


I have invoice object and it has two properties, productDescription and productQuantity, here is the code:

public class Invoice() implements Cloneable
{
  private String productDescription;
  private int productQuantity;

  //Getters & Setters

  public Object clone() throws CloneNotSupportedException {
     return super.clone();
  }
}

Now i want to create copy of object on this class so am doing

Invoice invoiceCopy = (Invoice)invoice.clone();

Now if i update value of invoiceCopy.setProductQuanity = 10 then invoice also updates the value but that should not happen, any suggestions?

Updated Code

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());
    }
}

Solution

  • default clone methode is a superficial one. you have to write yourself a new method or use a library that does what you want (see apache's BeanUtils for exemple)

    if you want to write it, try something like :

    public class Invoice implements Cloneable {
    private String productDescription;
    private int productQuantity;
    
    public Invoice() {
    }
    
    public Invoice(Invoice copy) {
        productDescription = copy.productDescription;
        productQuantity = copy.productQuantity;
    }
    
    public Object clone() throws CloneNotSupportedException {
        return new Invoice(this);
    }
    

    }