Why can I access the private members of an enclosing class reference

前端 未结 3 1698
有刺的猬
有刺的猬 2021-01-19 18:42

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 cod

相关标签:
3条回答
  • 2021-01-19 18:59

    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.

    0 讨论(0)
  • 2021-01-19 19:07

    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;
    }
    
    0 讨论(0)
  • 2021-01-19 19:16

    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.

    0 讨论(0)
提交回复
热议问题