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). I know that an inner class can access the enclosing class members directly by an implicit 'this' reference. But here, class B is static, so the 'this' reference won't apply.
B
is a member of A
and therefore has access to A
's private
fields and methods.
In this case, although B
is static
it is using an instance of A to access the field A.outerString
.
static
methods of a class can access private
members of the same class through the same class instance. This behavior is consistent for static
classes as well.
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.
2. And you can very well access the Outer class private member
from the (Top level) inner static class.
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.
上一篇: Java中的静态嵌套类,为什么?
下一篇: 为什么我可以访问封闭类引用的私有成员?