Java 中受保护的引用

protected references in Java

我有三个 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
    }
}

为什么我们不能从另一个包中访问受保护的成员,但我们可以从同一个包中访问?它们都是其中一个的子class,因此应该允许访问。

JLS 6.6.2.1 说:

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.

class C 满足要求。怎么了?

protected成员只能通过继承在包外的子类中访问。试试这个:

public class C extends A {

    void foo() {
       int b = i;  
    }
}

Class A 是包 pac 的一部分;

和 Class C 是软件包 another.pac 的一部分,因此它将无法访问其成员。如果 C 是包 pac 的一部分,那么它将能够访问成员

见下文post:In Java, difference between default, public, protected, and private

不用每次都做参考。我觉得你没看懂Inheritence..

public class B extends A {

    void foo() {
       // A a = new A(); No need to instantiate it here as B extends A
        int b = i;  //No nedd to refer it through a.a.i  
    }
}

package another.pac;

public class C extends A {

    void foo() {
        C c=new C();
        int d=c.i//this will work fine
       //   A a = new A(); same as above explanation
        int b = i;  //same as above and even a.i will not compile
    }
}

现在您的受保护变量可以在这里访问了..