Java Reference
In-Depth Information
PITFALL: (continued)
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 variable 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 modifier 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?
11. Suppose class D is derived from class B , the method doStuff() has protected
access in class B , and the classes D and B are in different packages, so the class def-
initions begin as follows:
package one;
public class B
{
protected void doStuff()
{
...
}
package two;
import one.B;
public class D extends B
{
...
}
Is the following a legitimate method that can appear in the definition of the class D ?
public void demo()
{
doStuff(); //doStuff is inherited from B.
}
(continued)
Search WWH ::




Custom Search