[英]Access to Private Members of a Superclass
What is the example of indirect access to private member of superclass from subclass? 从子类间接访问超类私有成员的示例是什么?
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. 因此,子类继承的公共或受保护嵌套类可以间接访问超类的所有私有成员。
Quote from http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html 引自http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
In the quote, we talk about "nested" class 在引用中,我们讨论“嵌套”类
here is an example of how an inner class can access private fields of the outer class. 这是一个内部类如何访问外部类的私有字段的示例。
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();
}
} }
Finally, if you extend a class with the InnerClass, they will also access the private fields of the OuterClass if your InnerClass is public or protected 最后,如果使用InnerClass扩展类,如果您的InnerClass是公共的或受保护的,它们也将访问OuterClass的私有字段
It is to be supposed (but the compiler does not enforce it, only warns), that a private
method will end being used by a public
, protected
or default method (otherwise it is useless). 应该假设(但是编译器不强制执行它,只发出警告), private
方法将被public
, protected
或默认方法使用(否则它是无用的)。
So, the extending class can "indirectly" call the private
method by calling the public
, protected
or default method that ends calling the private method. 因此,延伸类可以“间接”调用private
通过调用方法public
, protected
是结束调用私有方法或默认的方法。
Yes, we can access private members of a superclass in the child class through the public method of the superclass which can be invoked from the child class's reference variable heaving the reference id of child class. 是的,我们可以通过超类的公共方法访问子类中超类的私有成员,该方法可以从子类的引用变量中调用,并引用子类的引用ID。 for example:- 例如:-
class Base
{
private int x=10;
void show()
{
System.out.println(x);
}
}
class Child extends Base
{
public static void main(String... s)// public static void main(String[] args)
{
//rom jdk 1.7 main can be defined like above
Child c=new Child();
c.show();
}
}
The output will be 10 输出将是10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.