What does “qualified this” construct mean in java?

早过忘川 提交于 2020-01-09 07:11:28

问题


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?


回答1:


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*/
    }
  }
}



回答2:


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.



来源:https://stackoverflow.com/questions/11276994/what-does-qualified-this-construct-mean-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!