Java Reference
In-Depth Information
PITFALL: (continued)
The following is also a legitimate method definition for the derived class
D
:
public void
demo2()
{
D object =
new
D();
object.n = 42;
//n is inherited from B.
}
However, the following is not allowed as a method of
D
:
public void
demo3()
{
B object =
new
B();
object.n = 42;
//Error
}
The compiler will give an error message saying that
n
is protected in
B
.
Similar remarks apply to protected methods.
A class can access its own classes' inherited variables and methods that are marked
protected in the base class, but cannot directly access any such instance variables or
methods of an object of the base class (or of any other derived class of the base class).
In the above example,
n
is an instance variable of the base class
B
and an instance vari-
able of the derived class
D
.
D
can access
n
whenever
n
is used as an instance variable of
D
, but
D
cannot access
n
when
n
is used as an instance variable of
B.
If the classes
B
and
D
are in the same package, you will not get the error message
because, in Java, protected access implies package access. In particular, if the classes
B
and
D
are both in the default package, you will not get the error message.
■
Self-Test Exercises
9. Suppose you change the modifi er before the instance variable
name
from
private
to
protected
in the class
Employee
( Display 7.2 ). Would it then be
legal to add the method
crazyMethod
(from Self-Test Exercise 7 ) to the class
HourlyEmployee
( Display 7.3 )?
10. Which is more restricted, protected access or package access?
(continued)