从扩展外部类本身的内部类中访问外部类成员 [英] Accessing outer class members from within an inner class extending the outer class itself
问题描述
在下面显示的代码片段中,内部类本身继承外部类。
In the code snippet shown below, an inner class inherits an outer class itself.
package test;
class TestInnerClass {
private String value;
public TestInnerClass(String value) {
this.value = value;
}
private String getValue() {
return value;
}
public void callShowValue() {
new InnerClass("Another value").showValue();
}
private final class InnerClass extends TestInnerClass {
public InnerClass(String value) {
super(value);
}
public void showValue() {
System.out.println(getValue());
System.out.println(value);
}
}
}
public final class Test {
public static void main(String[] args) {
new TestInnerClass("Initial value").callShowValue();
}
}
内的唯一声明main()
方法(最后一个片段)将值初始值
分配给私有字段 value
TestInnerClass
类,然后调用 callShowValue()
方法。
The only statement inside the main()
method (the last snippet) assigns the value Initial value
to the private field value
of the TestInnerClass
class and then invokes the callShowValue()
method.
callShowValue()
方法导致另一个字符串 - 另一个值
被设置为私有调用 showValue()
TestInnerClass 类的字段 value
> InnerClass的方法
扩展 TestInnerClass
。
The callShowValue()
method causes another string - Another value
to be set the to the private field value
of the TestInnerClass
class before invoking the showValue()
method of InnerClass
extending TestInnerClass
.
相应地, showValue()
方法中的以下两个语句,
Accordingly, the following two statements inside the showValue()
method,
System.out.println(getValue());
System.out.println(value);
应显示,
另一个值
另一个值
Another value
Another value
但它们会显示,
初始值
初始值
Initial value
Initial value
为什么会发生这种情况吗?
Why does this happen?
推荐答案
方法 getValue()
和字段 value
都是 private
。因此,任何其他类都无法访问它们,包括子类,即。它们不是继承的。
The method getValue()
and the field value
are both private
. As such, they are not accessible to any other classes, including sub-classes, ie. they are not inherited.
在 InnerClass#showValue()
public void showValue() {
System.out.println(getValue());
System.out.println(value);
}
因为这些是私有的, getValue ()
和 value
指的是外部类的成员,因为你在同一个类中,所以可以访问它们,即。 内部类可以访问外部类私有成员。上述调用相当于
because of the fact that those are private, getValue()
and value
are referring to the outer class' members, which are accessible because you are in the same class, ie. inner classes can access outer class private members. The above calls are equivalent to
public void showValue() {
System.out.println(TestInnerClass.this.getValue());
System.out.println(TestInnerClass.this.value);
}
因为你设置了值
as
new TestInnerClass("Initial value")
你看到初始值
被打印两次。 无法访问子类中的私有
成员。
you see "Initial value"
being printed twice. There is no way to access those private
members in the sub-class.
重点是:不要让子类成为内部类。
The point is: don't make sub classes inner classes.
这篇关于从扩展外部类本身的内部类中访问外部类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!