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 avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18324)
- How to add BASIC Authentication into HttpURLConnection?(16080)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13988)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10445)