Java Reference
In-Depth Information
PITFALL: (continued)
is more dramatic. A private variable can be accessed indirectly via an accessor or
mutator method. A private method is simply not available. It is just as if the private
method were not inherited. (In one sense, private methods in the base class may be
indirectly available in the derived class. If a private method is used in the definition
of a public method of the base class, then that public method can be invoked in the
derived class, or any other class, so the private method can be indirectly invoked.)
This should not be a problem. Private methods should just be used as helping
methods, so their use should be limited to the class in which they are defi ned. If you
want a method to be used as a helping method in a number of inherited classes, then
it is not
just
a helping method, and you should make the method public.
■
Protected and Package Access
As you have seen, you cannot access (by name) a private instance variable or private
method of the base class within the definition of a derived class. There are two
classifications of instance variables and methods that allow them to be accessed by
name in a derived class. The two classifications are
protected access
, which always gives
access, and
package access
, which gives access if the derived class is in the same package
as the base class.
If a method or instance variable is modified by
protected
(rather than
public
or
private
), then it can be accessed by name inside its own class definition, it can
be accessed by name inside any class derived from it, and it can also be accessed by
name in the definition of any class in the same package (even if the class in the same
package is not derived from it). However, the
protected
method or instance variable
cannot be accessed by name in any other classes. Thus, if an instance variable is marked
protected
in the class
Parent
and the class
Child
is derived from the class
Parent
,
then the instance variable can be accessed by name inside any method definition in the
class
Child
. However, in a class that is not in the same package as
Parent
and is not
derived from
Parent
, it is as if the
protected
instance variable were
private
.
For example, consider the class
HourlyEmployee
that was derived from the
base class
Employee
. We were required to use accessor and mutator methods to
manipulate the inherited instance variables in the definition of
HourlyEmployee
.
Consider the definition of the
toString
method of the class
HourlyEmployee
,
which we repeat here:
public
String toString()
{
return
(getName() + " " + getHireDate().toString()
+ "\n$" + wageRate + " per hour for " + hours + " hours");
}