Java Reference
In-Depth Information
PITFALL: (continued)
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 methods must be as we described, or else they would be compromised. If
private instance variables of a class were accessible in method defi nitions of a derived
class, then anytime you want to access a private instance variable, you could simply
create a derived class and access it in a method of that class, which 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 uninten-
tional errors, not intentional 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 inappropriate 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.”
■
Self-Test Exercises
7. Would the following be legal for the defi nition of a method to add to the class
Employee
(Display 7.2)? (Remember, the question is whether it is legal, not
whether it is sensible.)
public void
crazyMethod()
{
Employee object =
new
Employee("Joe",
new
Date("January", 1, 2005));
System.out.println("Hello " + object.name);
}
Would it be legal to add this
crazyMethod
to the class
HourlyEmployee?
8. Suppose you change the modifi er before the instance variable
name
from
private
to
public
in the class
Employee
. Would it then be legal to add the
method
crazyMethod
(from Self-Test Exercise 7) to the class
HourlyEmployee
?
PITFALL: Private Methods Are Effectively Not Inherited
As we noted in the Pitfall section, “Use of Private Instance Variables from the Base
Class,” an instance variable (or method) that is private in a base class is not directly
accessible outside of the definition of the base class,
not even in a method definition
for a derived class
. The private methods of the base class are just like private variables
in terms of not being directly available. But in the case of methods, the restriction