从子类间接访问父类(super class)私有(private)成员的例子是什么?
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
最佳答案
在引用中,我们谈论“嵌套”类
这是一个内部类如何访问外部类的私有(private)字段的示例。
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 是公共(public)的或 protected ,他们也将访问 OuterClass 的私有(private)字段
关于java - 访问父类(super class)的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14521324/