Witscale Test Center

4.4 Non-static member class (aka member inner class) > 4.4.3 Accessibility of variables


4.4.3 Accessibility of variables

A member inner class has unprecedented access to all member variables and methods of the outer class. This accessibility of members of the enclosing class is very useful feature of inner classes. Listing 4.2 illustrates how inner class InnerOne can access the enclosing class’s member variables.


 

The member variable outerVar is being accessed by InnerOne in the same fashion it is accessing its own variable, innerVar. The outerVar is a private variable, but it is still accessible to the inner class. Inner class always has an access to member variable of enclosing class no matter what its access modifier is. The inner class can also invoke member methods in similar fashion.  For example, the accessibilityTest() method calls the outerMethod() of the enclosing class. Thus the member inner class always has an access to member methods of enclosing class no matter what access modifier the method is using.  We can test the code in listing 4.2 as:

 

package com.example.scjp.studykit;

public class Tester {

   public static void main(String[] args) {

         OuterOne outer = new OuterOne();

         OuterOne.InnerOne inner = outer.new InnerOne();

         inner.accessibilityTest();

   }

}

 

This kind of accessibility is possible as the inner class has an implicit reference to enclosing class’s instance on which it is created. For example, the InnerOne class’s instance inner has an implicit reference to outer. (enclosing class’s instance on which inner is created). When we invoke inner.accessibilityTest(), it can call the outerMethod() of enclosing instance outer.