Monday, 10 August 2015

ClassName.this : Access instance of enclosing class

To access the instance of the enclosing-class from inside the inner classes or the anonymous classes, you need to use Classname.this.

public class Test {

 int x = 10;

 interface Sample {
  void print();
 }

 Sample sample = new Sample() {
  int x = 20;

  @Override
  public void print() {
   System.out.println("Test.this.x = " + Test.this.x);
   System.out.println("x = " + x);
  }

 };
 
 public static void main(String args[]){
  Test test = new Test();
  test.sample.print();
 }

}

Output
Test.this.x = 10
x = 20



No comments:

Post a Comment