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.
1.
this
only works with non-static member, thats right..... But you are not usingthis
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 forstatic inner class
you must access using the Instance.B
is a member ofA
and therefore has access toA
'sprivate
fields and methods.In this case, although
B
isstatic
it is using an instance of A to access the fieldA.outerString
.static
methods of a class can accessprivate
members of the same class through the same class instance. This behavior is consistent forstatic
classes as well.