Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "qualified this" construct mean in java?

Tags:

java

jls

In Effective Java inside the item "Item 22: Favor static member classes over nonstatic" Josh Bloch says:

Each instance of a nonstatic member class is implicitly associated with an enclosing instance of its containing class. Within instance methods of a nonstatic member class, you can invoke methods on the enclosing instance or obtain a reference to the enclosing instance using the qualified this construct.

What does he mean by Qualified This Construct?

like image 891
Inquisitive Avatar asked Jun 30 '12 19:06

Inquisitive


People also ask

What is a qualified method name in Java?

A qualified name consists of a name, a " . " token, and an identifier. In determining the meaning of a name (§6.5), the Java language takes into account the context in which the name appears. It distinguishes among contexts where a name must denote (refer to) a package (§6.5.

How does this work in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).


2 Answers

Without the qualifier, x() would recurse. With the qualifier, the enclosing instance's x() method is invoked instead.

class Envelope {   void x() {     System.out.println("Hello");   }   class Enclosure {     void x() {       Envelope.this.x(); /* Qualified*/     }   } } 
like image 159
erickson Avatar answered Oct 03 '22 04:10

erickson


A non-static member class has an implicit reference to an instance of the enclosing class. The Qualified This term refers to the instance of the enclosing class. If the enclosing class is A, and the inner class is B, you can address the enclosing reference of A from B as A.this.

like image 24
Paul Morie Avatar answered Oct 03 '22 04:10

Paul Morie