Java Reference
In-Depth Information
PITFALL: A Restriction on Protected Access
The situation described in this pitfall does not occur often, but when it does occur, it can
be very puzzling if you do not understand what is going on.
Suppose class D is derived from class B , the instance variable n has protected access in
class B , and the classes D and B are in different packages, so the class definitions begin as
follows:
package one;
public class B
{
protected int n;
...
}
package two;
import one.B;
public class D extends B
{
...
}
Then the following is a legitimate method that can appear in the definition of class D :
public void demo()
{
n = 42; //n is inherited from B.
}
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 n is protected in B .
Search WWH ::




Custom Search