Java Reference
In-Depth Information
PITFALL: (continued)
This
return
statement does not return the reference in the private instance variable
born
.
Instead, it uses the copy constructor to return a reference to a new object that is an exact
copy of the object named by
born
. If the copy is changed, that has no effect on the date
whose reference is in the instance variable
born
. Thus, a privacy leak is avoided.
Note that returning a reference is not the only possible source of privacy leaks.
A privacy leak can also arise from an incorrectly defi ned constructor or mutator
method. Notice the defi nition for the method
setBirthDate
in Display 5.19 and
reproduced as follows:
leaking
mutator
methods
public void
setBirthDate(Date newDate)
{
if
(consistent(newDate, died))
born =
new
Date(newDate);
else
{
System.out.println("Inconsistent dates. Aborting.");
System.exit(0);
}
}
Note that the instance variable
born
is set to a copy of the parameter
newDate
.
Suppose that instead of
born =
new
Date(newDate);
we simply use
born = newDate;
And suppose we use the following code in some program:
Person personObject =
new
Person(
"Josephine",
new
Date("January", 1, 2000),
null
);
Date dateName =
new
Date("February", 2, 2002);
personObject.setBirthDate(dateName);
where
personObject
names an object of the class
Person
. The following will change
the year part of the
Date
object named by the
born
instance variable of the object
personObject
and will do so without going through the checks in the mutator
methods for
Person
:
dateName.setYear(1000);
(continued)