[英]Why can I access the private members of an enclosing class reference
I have seen many questions about accessing private members of an enclosing class. 我已经看到很多关于访问封闭类的私人成员的问题。 However, my question is the opposite. 但是,我的问题恰恰相反。
If I have (as an example), the following code: 如果我(作为示例),以下代码:
public class A {
private String outerString = "silly string";
static class B {
private final A someA = new A();
public void foo() {
String b = someA.outerString ;
}
}
}
I'm wondering why this compiles? 我想知道为什么这个编译? I would have expected an error by virtue of the way in which I am accessing the 'outerString' instance variable from class A (via someA.outerString). 我希望通过我从类A(通过someA.outerString)访问'outerString'实例变量的方式来预测错误。 I know that an inner class can access the enclosing class members directly by an implicit 'this' reference. 我知道内部类可以通过隐式的“this”引用直接访问封闭的类成员。 But here, class B is static, so the 'this' reference won't apply. 但是在这里,B类是静态的,因此'this'引用不适用。
B
is a member of A
and therefore has access to A
's private
fields and methods. B
是A
的成员,因此可以访问A
的private
字段和方法。
In this case, although B
is static
it is using an instance of A to access the field A.outerString
. 在这种情况下,尽管B
是static
,但它使用A的实例来访问字段A.outerString
。
static
methods of a class can access private
members of the same class through the same class instance. static
方法可以通过同一个类实例访问同一个类的private
成员。 This behavior is consistent for static
classes as well. 这种行为对于static
类也是一致的。
static void b(A someA) {
String b = someA.outerString;
}
1. this
only works with non-static member, thats right ..... But you are not using this
but instance of the Outer Class. 1. this
只是非静态成员的作品,这就是正确的 .....但你不使用 this
,但外部类的实例。
2. And you can very well access the Outer class private member
from the (Top level) inner static class. 2.您可以从(顶级)内部静态类 访问 Outer class private member
。
3. Outer to Inner and from Inner to Outer has the ability to access the private member of each other .. only difference is that, non static inner class
has implicit reference to the Outer class , and for static inner class
you must access using the Instance. 3.从外到内,从内到外有能力访问彼此的私有成员 .. 唯一不同的是, non static inner class
具有对外部类的隐式引用 ,对于static inner class
您必须使用实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.