Java Reference
In-Depth Information
PITFALL: Use of Private Instance Variables from the Base Class
An object of the class HourlyEmployee ( Display 7.3 ) inherits, among other things, an
instance variable called name from the class Employee ( Display 7.2 ). For example, the
following would set the value of the instance variable name of the HourlyEmployee
object joe to "Josephine" :
joe.setName("Josephine");
But you must be a bit careful about how you manipulate inherited instance variables
such as name . The instance variable name of the class HourlyEmployee was inherited
from the class Employee , but the instance variable name is a private instance variable
in the definition of the class Employee . That means that name can only be accessed by
name within the definition of a method in the class Employee . An instance variable
(or method) that is private in a base class is not accessible by name in the definition of
a method in any other class, not even in a method definition of a derived class .
For example, notice the following method defi nition taken from the defi nition of
the class HourlyEmployee in Display 7.3 :
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 .
You 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 such as 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 defi nition 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 defi ned in the base class.
The fact that a private instance variable of a base class cannot be accessed in the def-
inition 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 .” If you are an hourly employee, you
(continued)
 
Search WWH ::




Custom Search