32

Effective Java 中的项目“第 22 项:支持静态成员类而不是非静态”中,Josh Bloch 说:

非静态成员类的每个实例都隐含地与其包含类的封闭实例相关联。在非静态成员类的实例方法中,您可以调用封闭实例上的方法或使用限定的 this 构造获取对封闭实例的引用。

他所说的Qualified This Construct是什么意思?

4

2 回答 2

41

没有限定符,x()将递归。使用限定符,将x()调用封闭实例的方法。

class Envelope {
  void x() {
    System.out.println("Hello");
  }
  class Enclosure {
    void x() {
      Envelope.this.x(); /* Qualified*/
    }
  }
}
于 2012-06-30T19:40:08.057 回答
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.

于 2012-07-01T00:51:55.767 回答