July 18, 2011

Access outer class instance from within the inner class method

MyOuter is the outer class which contains MyInner which is the inner class. The seeOuter() method within the inner class can access the inner class instance with the this keyword. In order to access the outer class instance from within the seeOuter() method, the syntax is use the outer class name with the this keyword - the syntax looks like this: OuterClassName.this

The code example below demonstrates the same,

package info.icontraining.basic;

public class MyOuter {
     private int x = 3;
 
   class MyInner {
      private int x = 5;
  
      public void seeOuter() {
         System.out.println("Inner x is = " + this.x);
         System.out.println("Outer x is = " + MyOuter.this.x );
      }
   }
 
   public static void main(String[] args) {
      MyOuter.MyInner inner = new MyOuter().new MyInner();
      inner.seeOuter();
   }
}

No comments:

Post a Comment