java inner/outer class questions about outer class private variables access

后端 未结 2 588
自闭症患者
自闭症患者 2020-12-29 07:32

I have the following java class:

class Outer
{
    private Integer a;
    private Long b;

    class Inner
    {
        public void foo()
        { 
                


        
2条回答
  •  心在旅途
    2020-12-29 08:17

    Non-static inner classes have an implicit reference to an instance of the outer class. This is implemented as a final reference to the outer class. If it wasn't final technically it could be modified after instantiation.

    The outer class is implicitly passed in which is why any constructors on the inner class have an implicit parameter of the outer class, which is how this$0 is passed in.

    Edit: as for the access$000 methods the key clue is that they're package access and they take an Outer as an argument. So when code in Inner calls, say, Inner.this.a it's actually calling Inner.access$000(this$0). So those methods are there to give access to private members of the outer class to the inner class.

提交回复
热议问题