I thought inner classes could access the outer class variables/methods?

前端 未结 5 1160
后悔当初
后悔当初 2020-12-09 10:18

I did read a number of topics discussing inner classes, and i was under the impression that an inner class has access to the variables and methods of the enclosing class. In

5条回答
  •  无人及你
    2020-12-09 10:50

    inner is an instance of OuterClass.InnerClass which doesn't defines a so it wont be able to access it anyways.

    To understand it in the simplest manner... look at the block in which a is created and the block in which OuterClass.InnerClass is defined.

    public class OuterClass { // a is defined in this block
    
        String a = "A";
    
        class InnerClass{ // InnerClass starts here and an instance will access what is defined now
            int x;
        }
    }
    

提交回复
热议问题