Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
How to use keyword 'this' in an inner class?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: How to use keyword 'this' in an inner class?

How to use keyword 'this' in an inner class?

According to the 15.8.3 this:

The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

When used as a primary expression, the keyword this denotes a value, that is a reference to the object for which the instance method was invoked, or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.

The name this.x refers to a variable named x in this instance of the object. It is pretty obvious that if you refer to this in an inner class, it refers to fields or variables defined in the inner class itself.

The following code outputs 20 because this.a refer to variable a in the inner class not in the outer class:

class Outer {
  private int a=10;
  class Inner {
     private int a=20;
     public void myMethod() {
         System.out.println(this.a);
     }
  }
}

How could we possibly to access the variable a in the outer class? The answer is the qualified this.

According to the 15.8.4 Qualified this, the syntax of qualified this is ClassName.this. The prepended class name merely verifies that you are indeed referring to an instance of the named class. This notation is always effective, since the language prohibits an inner class from having the same name as any of its enclosing classes.

In all classes, each current instance can be named explicitly or can play an implicit part when its members are used. Any current instance can be referred to by explicitly qualifying the keyword this as if it were a name: ClassName.this . As always, the innermost current instance can be named with the unqualified keyword this.

class Outer {
  private int a=10;
  class Inner {
     private int a=20;
     public void myMethod() {
         System.out.println(Outer.this.a);
     }
  }
}

References

How do inner classes affect the idea of this in Java code?


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help