How to use keyword 'this' in an inner class?
According to the 15.8.3 this:
The keyword
thismay 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
thisdenotes a value, that is a reference to the object for which the instance method was invoked, or to the object being constructed. The type ofthisis the class C within which the keywordthisoccurs. 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?
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?