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

java – 封闭类型的静态嵌套子类仍然可以引用私有字段成员,为什

发布时间:2020-12-15 04:36:48 所属栏目:Java 来源:网络整理
导读:我找到了一些含糊不清的恕我直言.假设我们有以下类结构: public class A{ private int privateVar = 1; protected int protectedVar = 2; static class B extends A { public int getPrivateVariable() { return privateVar; //error: Cannot make a static
我找到了一些含糊不清的恕我直言.假设我们有以下类结构:

public class A
{
    private int privateVar = 1;
    protected int protectedVar = 2;

    static class B extends A
    {
        public int getPrivateVariable()
        {
            return privateVar; //error: Cannot make a static reference to the non-static field memberVariable
        }

        public int getProtectedVariable()
        {
            return protectedVar; //OK: Why?
        }

        public int getPrivateUnfair()
        {
            return super.privateVar; //Why this can be accessed using super which the protected member doesn't require.
        }
    }
}

>为什么静态嵌套类可以自由访问实例成员?
>为什么保护和私有变量的访问方式有所不同?但是,如果嵌套类是非静态内部类,那么情况并非如此?

编辑:

>为什么关键字super允许访问封闭类型的私有成员?

解决方法

  1. Why at all does the static nested class has free access to the instance members?

因为B扩展了A.你没有访问A的成员变量,你正在访问B的继承成员变量.

  1. Why there is a difference in the way protected and private variables can be accessed? This however,is not the case if the nested class is non-static inner class?

因为私有字段不是继承的,而受保护的字段是;但是私有字段仍然存在于超类中,并且通过super可见,因为B嵌套在A中.可见性修饰符的表达方式不足以表达与通过super访问相同的内容.

(编辑:李大同)

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

    推荐文章
      热点阅读