从子类间接访问超类私有成员的示例是什么?
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
最佳答案
在引用中,我们讨论“嵌套”类
原文链接:https://www.f2er.com/java/438302.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的私有字段