Wednesday, May 13, 2009

Java's "protected" access fine print

In Java, protected means that subclasses have access, even if the classes are in different packages. This is actually not always the case. Right from Java's language spec:

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.


The following code produces a compile error.


package p1;

public class C1
{
protected void foo()
{
}
}

...

package p2;

import p1.C1;

public class C2 extends C1
{
private C1 c1;
private void bar()
{
c1.foo(); // compile error
}
}


I have yet to understand why this is the case. I'm guessing it has something to do with virtual methods and identifier resolution tokens.

1 comment:

Andy said...

Because you can't access protected methods of a class. You have to call foo() directly from inside C2.