Java Reference
In-Depth Information
This version, which we did use, makes the instance variable
this.born
an indepen-
dent
Date
object that represents the same date as
original.born
. So if you change a
date in the
Person
object created by the copy constructor, you will not change that
date in the
original
Person
object.
Note that if a class, such as
Person
, has instance variables of a class type, such as the
instance variables
born
and
died
, then to define a correct copy constructor for the class
Person
, you must already have copy constructors for the class
Date
of the instance
variables. The easiest way to ensure this for all your classes is to always include a copy
constructor in every class you define.
Copy Constructor
A
copy constructor
is a constructor with one parameter of the same type as the class. A
copy constructor should be designed so the object it creates is intuitively an exact copy of
its parameter, but a completely independent copy. See Displays 5.19 and 5.20 for exam-
ples of copy constructors.
The Java documentation says to use a method named
clone
instead of a copy con-
structor, and, as you will see later in this topic, there are situations where the copy con-
structor will not work as desired and you need the
clone
method. However, we do not
yet have enough background to discuss the
clone
method. The
clone
method is dis-
cussed later in this topic (Chapters 8 and 13). Despite the Java documentation, many
excellent programmers prefer to sometimes use copy constructors. In this topic, we
will use both copy constructors and the
clone
method.
clone
PITFALL: Privacy Leaks
Consider the accessor method
getBirthDate
for the class
Person
(Display 5.19),
which we reproduce in what follows:
leaking
accessor
methods
public
Date getBirthDate()
{
return
new
Date(born);
}
Do not make the mistake of defining the accessor method as follows:
public
Date getBirthDate()
//Unsafe
{
return
born;
//Not good
}
(continued)