Java Reference
In-Depth Information
Self-Test Exercises
(continued)
40. What output is produced by the following code?
Person original =
new
Person("Natalie Dressed",
new
Date("April", 1, 1984),
null
);
Person copy =
new
Person(original);
copy.setBirthDate(
new
Date("April", 1, 1800));
System.out.println(original)
Mutable and Immutable Classes
Contrast the accessor methods
getName
and
getBirthDate
of the class
Person
(Display
5.19). We reproduce the two methods in what follows:
public
String getName()
{
return
name;
}
public
Date getBirthDate()
{
return
new
Date(born);
}
Notice that the method
getBirthDate
does not simply return the reference in the
instance variable
born
, but instead uses the copy constructor to return a reference to a
copy of the birth date object. We have already explained why we do this. If we return
the reference in the instance variable
born
, then we can place this reference in a vari-
able of type
Date
, and that variable could serve as another name for the private
instance variable
born
, which would allow us to violate the privacy of the instance vari-
able
born
by changing it using a mutator method of the class
Date
. This is exactly what
we discussed in the previous subsection. So why didn't we do something similar in the
method
getName
?
The method
getName
simply returns the reference in the private instance variable
name
. So, if we do the following in a program, then the variable
nameAlias
will be
another name for the
String
object of the private instance variable
name
:
Person citizen =
new
Person(
"Joe Citizen",
new
Date("January", 1, 1900),
new
Date("January", 1, 1990));
String nameAlias = citizen.getName();