Protected references in Java

See English answers > understanding Java's protected modifier 6

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 protected members from being put into another package, but we can access them from the same package? They are all subclasses of a, so access should be allowed

JLS 6.6. 2.1 say:

Grade C is satisfactory What's up?

Solution

Protected members can only be accessed through inheritance in subclasses outside the package Try this:

public class C extends A {

    void foo() {
       int b = i;  
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>