Java Reference
In-Depth Information
We want the object created to be an independent copy of
original
. That would
not happen if we had used the following instead:
public
Person(Person original)
//Unsafe
{
if
(original ==
null
)
{
System.out.println("Fatal error.");
System.exit(0);
}
name = original.name;
born = original.born;
//Not good.
died = original.died;
//Not good.
}
Although this alternate definition looks innocent enough and may work fine in many
situations, it does have serious problems.
Assume we had used the unsafe version of the copy constructor instead of the one
in Display 5.19. The “Not good.” code simply copies references from
original.born
and
original.died
to the corresponding arguments of the object being created by the
constructor. So, the object created is not an independent copy of the
original
object.
For example, consider the code
Person original =
new
Person("Natalie Dressed",
new
Date("April", 1, 1984),
null
);
Person copy = new Person(original);
copy.setBirthYear(1800);
System.out.println(original);
The output would be
Natalie Dressed, April 1, 1800-
When we changed the birth year in the object
copy
, we also changed the birth year
in the object
original
. This is because we are using our unsafe version of the copy
constructor. Both
original.born
and
copy.born
contain the same reference to the
same
Date
object.
This all happens because we used the unsafe version of the copy constructor.
Fortunately, here we use a safer version of the copy constructor that sets the
born
instance variables as follows:
born =
new
Date(original.born);
which is equivalent to
this
.born =
new
Date(original.born);