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

java – 访问超类的私有成员

发布时间:2020-12-14 06:07:55 所属栏目:Java 来源:网络整理
导读:从子类间接访问超类私有成员的示例是什么? A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore,a public or protected nested class inherited by a subclass has indirect access to all

从子类间接访问超类私有成员的示例是什么?

A nested class has access to all the private members of its enclosing
class—both fields and methods. Therefore,a public or protected nested
class inherited by a subclass has indirect access to all of the
private members of the superclass.

报价从http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

最佳答案
在引用中,我们讨论“嵌套”类

这是一个内部类如何访问外部类的私有字段的示例.

class OuterClass {
private int x = 7;

public void makeInner(){
    InnerClass in = new InnerClass();
    in.seeOuter();
}
class InnerClass {
    public void seeOuter() {
        System.out.println("Outer x is " + x);
    }
}
public static void main(String[] args) {
    OuterClass.InnerClass inner = new OuterClass().new InnerClass();
    inner.seeOuter();
}

}

最后,如果使用InnerClass扩展类,如果您的InnerClass是公共的或受保护的,它们也将访问OuterClass的私有字段

(编辑:李大同)

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

    推荐文章
      热点阅读