Java Reference
In-Depth Information
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
. For example, 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");
}
If the private instance variables
name
and
hireDate
had been marked
protected
in
the class
Employee
, the definition of
toString
in the derived class
HourlyEmployee
could be simplified to the following:
public
String toString()
//Legal if instance variables in
// Employee are marked protected
{
return
(name + " " + hireDate.toString()
+ "\n$" + wageRate + " per hour for " + hours + " hours");
}
The
protected
Modifier
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, by name inside any class
derived from it, and by name in the definition of any class in the same package.
The
protected
modifier provides very weak protection compared to the
private
modifier, since it allows direct access to any programmer who is willing to go through
the bother of defining a suitable derived class. Many programming authorities discour-
age the use of the
protected
modifier. Instance variables should normally not be
marked
protected
. On rare occasions, you may want to have a method marked