Search code examples
javajls

Java protected modifier


I have just got weird error which involves protected modifier.

I have following code:

package p1;

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


package p2;

public class C2 extends p1.C1 {
    private C1 c1_instance;
    public void doItAgain() {
        c1_instance.doIt(); // wtf!!!!
    }
}

I get error, stating that doIt() has protected access and can't be accessed! But I am in the sub class and do have and access to doIt() method.

Is not it a bug?


Solution

  • I also had the impression what protected meant "accessible from the same package or from a subclass" but the Java Language Specification is of course more precise, and explains that in a subclass S of C, "If the access is by a qualified name Q.Id, where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S."

    So you can only access a protected method of the superclass via a reference to the subclass you are calling from, like this:

    public class C2 extends C1 {
        private C2 c2_other_instance;
        public void doItAgain() {
            c2_other_instance.doIt();
        }
    }
    

    If you explain why you want to access one instance of the superclass from a different instance of the subclass then someone might be able to suggest a better design. Otherwise you will have to make the method public or put the classes in the same package.