Java Reference
In-Depth Information
PITFALL:
(continued)
public
String toString()
{
return
(getName() + " " + getHireDate().toString()
+ "\n$" + wageRate + " per hour for " + hours + " hours");
}
You might wonder why we needed to use the methods
getName
and
getHireDate
.
Yo u
might be tempted to rewrite the method definition as follows:
public
String toString()
//Illegal version
{
return
(name + " " + hireDate.toString()
+ "\n$" + wageRate + " per hour for " + hours + " hours");
}
As the comment indicates, this will not work. The instance variables
name
and
hireDate
are private instance variables in the class
Employee
, and although a derived class like
HourlyEmployee
inherits these instance variables, it cannot access them directly. You
must instead use some public methods to access the instance variable
name
or
hireDate
,
as we did in Display 7.3.
In the definition of a derived class, you cannot mention a private inherited instance
variable by name. You must instead use public accessor and mutator methods (such as
getName
and
setName
) that were defined in the base class.
The fact that a private instance variable of a base class cannot be accessed in the definition
of a method of a derived class often seems wrong to people. After all, if you are an hourly
employee and you want to change your name, nobody says, “Sorry,
name
is a private instance
variable of the class
Employee
.” After all, if you are an hourly employee, you are also an
employee. In Java, this is also true; an object of the class
HourlyEmployee
is also an object of
the class
Employee
. However, the laws on the use of private instance variables and meth-
ods must be as we described, or else they would be compromised. If private instance
variables of a class were accessible in method definitions of a derived class, then anytime
you wanted to access a private instance variable, you could simply create a derived class
and access it in a method of that class, and that would mean that all private instance
variables would be accessible to anybody who wants to put in a little extra effort. This
scenario illustrates the problem, but the big problem is unintentional errors, not inten-
tional subversion. If private instance variables of a class were accessible in method defi-
nitions of a derived class, then the instance variables might be changed by mistake or in
inappropriate ways. (Remember, accessor and mutator methods can guard against inap-
propriate changes to instance variables.)
We will discuss one possible way to get around this restriction on private instance
variables of the base class in the upcoming subsection entitled “Protected and Package
Access.”
■