Java Reference
In-Depth Information
PITFALL: (continued)
Assume we had used the unsafe version of getBirthDate instead of the one in Display
5.19. It would then be possible for a program that uses the class Person to change the
private instance variable born to any date whatsoever and bypass the checks in con-
structor and mutator methods of the class Person . For example, consider the following
code, which might appear in some program that uses the class Person :
Person citizen = new Person(
"Joe Citizen", new Date("January", 1, 1900), new Date("January", 1,
1990));
Date dateName = citizen.getBirthDate();
dateName.setDate("April", 1, 3000);
This code changes the date of birth so it is after the date of death (an impossibility in
the universe as we know it). This citizen was not born until after he or she died! This
sort of situation is known as a privacy leak , because it allows a programmer to cir-
cumvent the private modifier before an instance variable such as born and change
the private instance variable to anything whatsoever.
The following code would be illegal in our program:
privacy leak
citizen.born.setDate("April", 1, 3000); //Illegal
This is illegal because born is a private instance variable. However, with the unsafe
version of getBirthDate (and we are now assuming that we did use the unsafe ver-
sion), the variable dateName contains the same reference as citizen.born and so the
following is legal and equivalent to the illegal statement:
dateName.setDate("April", 1, 3000); //Legal and equivalent to illegal
one.
It is as if you have a friend named Robert who is also known as Bob. Some bully
wants to beat up Robert, so you say “You cannot beat up Robert.” The bully says
“OK, I will not beat up Robert, but I will beat up Bob.” Bob and Robert are two
names for the same person. So, if you protect Robert but do not protect Bob, you
have really accomplished nothing.
All this assumes that, contrary to fact, we have used the unsafe version of
getBirthDate , which simply returns the reference in the private instance variable
born . Fortunately, we used a safer version of getBirthDate , which has the follow-
ing return statement:
return new Date(born);
Search WWH ::




Custom Search