Search code examples
javaprotected

protected references in Java


I have three classes:

package pac;

public class A {
    protected A a;  
    protected final int i = 10;
}

public class B extends A {

    void foo() {
        A a = new A();
        int b = a.a.i;  //compiles fine
    }
}

package another.pac;

public class C extends A {

    void foo() {
        A a = new A();
        int b = a.a.i;  //Does not compile. a.a is inaccessible
    }
}

Why can't we access a protected member from a put into another package, but from the same package we can? They both are subclasses of one, therefore acces should have been permitted.

JLS 6.6.2.1 says:

If the access is by a field access expression E.Id, or a method invocation expression E.Id(...), or a method reference expression E :: Id, where E is a Primary expression (§15.8), then the access is permitted if and only if the type of E is S or a subclass of S.

The class C satisifies the requerement. What's wrong?


Solution

  • A protected member can be accessed in a subclass outside the package only through inheritance. Try this instead :

    public class C extends A {
    
        void foo() {
           int b = i;  
        }
    }