In Java, the assignment operator duplicates the reference, not the object. Because of this, the need of a method clone() to duplicate an object.
The default implementation of Object.clone() performs a shallow copy. To perform a deep copy, the method must be overridden, making sure to call the same method in the superclass.
This is an example of clone():
class Order implements Cloneable{ private Date paymentDate; public Object clone(){ try{ Order clone = (Order)super.clone(); clone.paymentDate = (Date)paymentDate.clone(); return clone; } catch(CloneNotSupportedException e){ System.out.println(e); return null; } } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date paymentDate) { this.paymentDate = paymentDate; } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.