Java Reference
In-Depth Information
PITFALL: (continued)
Because
dateName
contains the same reference as the private instance variable born
of the object
personObject
, changing the year part of
dateName
changes the year
part of the private instance variable born of
personObject
. Not only does this bypass
the consistency checks in the mutator method
setBirthDate
, but it also is a likely
source of an inadvertent change to the
born
instance variable.
If we defi ne
setBirthDate
as we did in Display 5.19 and as shown in the follow-
ing, this problem does not happen. (If you do not see this, go through the code step
by step and trace what happens.)
public void
setBirthDate(Date newDate)
{
if
(consistent(newDate, died))
born =
new
Date(newDate);
. . .
One final word of warning: Using copy constructors in this manner is not the
officially sanctioned way to make copies of an object in Java. The authorized way to is
to define a method named
clone
. We will discuss
clone
methods in Chapters 8 and 13 .
In Chapter 8, we show you that, in some situations, there are advantages to using a
clone
method instead of a copy constructor. In Chapter 13, we describe the official way
to define the
clone
method. For what we will be doing until then, a copy constructor
will be a very adequate way of creating copies of an object.
clone
Self Test Exercises
38. What is a copy constructor?
39. What output is produced by the following code?
Date date1 =
new
Date("January", 1, 2006);
Date date2;
date2 = date1;
date2.setDate("July", 4, 1776);
System.out.println(date1);
What output is produced by the following code? Only the third line is different
from the previous case.
Date date1 =
new
Date("January", 1, 2006);
Date date2;
date2 =
new
Date(date1);
date2.setDate("July", 4, 1776);
System.out.println(date1);