Few books explain that it is desirable for a class to provide a cloning operation.
Date tBirthDate = new DateImpl(2000, 1, 24);
Person tSomePerson = new PersonImpl("Joe", tBirthDate);
Do we share?
public class PersonImpl
{
private String iName;
private Date iDateOfBirth;
public PersonImpl(final String pName,
final Date pDateOfBirth)
{
iName = pName;
iDateOfBirth = pDateOfBirth; // share
...
Or do we clone?
iDateOfBirth = new DateImpl(pDateOfBirth); // clone
Note that you need not do this copying if the objects of the class
(in this case, the class DateImpl) are immutable.
It is best to provide a method called clone as this can be used when inheritance is involved. However, getting the code of a clone method completely right is difficult. See the article by Bill Venners at http://www.artima.com/innerjava/webuscript/cloning.html
Because it is hard to get right, it is also difficult to teach. Instead, I cheat by just providing a constructor that can be used for cloning:
public DateImpl(final Date pDate)
{
iYear = pDate.getYear();
iMonth = pDate.getMonth();
iDay = pDate.getDay();
}