加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java中的受保护引用

发布时间:2020-12-15 04:28:27 所属栏目:Java 来源:网络整理
导读:参见英文答案 Understanding java’s protected modifier????????????????????????????????????6个 ???????????? What is the difference between public,protected,package-private and private in Java?????????????????????????????????????24个 我有三个
参见英文答案 > Understanding java’s protected modifier????????????????????????????????????6个
>???????????? What is the difference between public,protected,package-private and private in Java?????????????????????????????????????24个
我有三个班:

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
    }
}

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

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.

C级令人满意.怎么了?

解决方法

只能通过继承在包外部的子类中访问受保护的成员.试试这个:

public class C extends A {

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读