36

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?

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
Inquisitive
  • 7,476
  • 14
  • 50
  • 61
  • 14
    `EnclosingType.this` –  Jun 30 '12 at 19:25
  • 3
    In computer science terminology a qualifier, or qualified identifier, is a name (selection path) `x.y.z`. This pre-dates java. – Joop Eggen Jun 30 '12 at 19:29
  • 1
    [Read all about it at the source.](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.4) – Marko Topolnik Jun 30 '12 at 19:35
  • @pst +1 since you answered in the comment itself. How do I accept your answer? – Inquisitive Jun 30 '12 at 19:40
  • @pst Since you were the first to answer, I suggest writing up a short answer. You can paste my link in there, too (from my comment above, it's a JLS link). – Marko Topolnik Jun 30 '12 at 19:45
  • 3
    One identifier is hardly an answer -- it needs some context as to *why* it is useful. I do not have enough time to give it justice at the moment. –  Jun 30 '12 at 20:04

2 Answers2

46

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*/
    }
  }
}
erickson
  • 265,237
  • 58
  • 395
  • 493
11

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.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
Paul Morie
  • 15,528
  • 9
  • 52
  • 57