public Object clone();
public class Date { ... public Object clone() { return super.clone(); } }
public class Date implements Cloneable { ... public Object clone() { try { return super.clone(); } catch(final CloneNotSupportedException pCloneNotSupportedException) { throw new InternalError(); } } }
Object's clone method only produces a shallow copy. So, if a class has one or more fields that are of a reference type, we may want to provide a deep copy by cloning these fields. For example, for the Person class, we could provide:
public class Person implements Cloneable { ... public Object clone() { try { final Person tPerson = (Person)super.clone(); if (iDateOfBirth!=null) { tPerson.iDateOfBirth = (Date)iDateOfBirth.clone(); } return tPerson; } catch(final CloneNotSupportedException pCloneNotSupportedException) { throw new InternalError(); } } }