Program Tip

내부 클래스에서 외부 클래스의 "this"에 어떻게 액세스 할 수 있습니까?

programtip 2020. 11. 14. 10:59
반응형

내부 클래스에서 외부 클래스의 "this"에 어떻게 액세스 할 수 있습니까?


thisJava 내부 클래스 내에서 참조를 얻을 수 있습니까?

class Outer {

  void aMethod() {

    NewClass newClass = new NewClass() {
      void bMethod() {
        // How to I get access to "this" (pointing to outer) from here?
      }
    };
  }
}

다음과 같이 외부 클래스의 인스턴스에 액세스 할 수 있습니다.

Outer.this

Outer.this

즉.

class Outer {
    void aMethod() {
        NewClass newClass = new NewClass() {
            void bMethod() {
                System.out.println( Outer.this.getClass().getName() ); // print Outer
            }
        };
    }
}

BTW Java에서 클래스 이름은 규칙에 따라 대문자로 시작합니다.


외부 클래스의 클래스 이름을 다음에 추가하십시오.

outer.this

예, 이것 과 함께 외부 클래스 이름을 사용할 수 있습니다 . 외부.이


추가 : 내부 클래스가 '정적'으로 선언되면 불가능합니다.

참고 URL : https://stackoverflow.com/questions/2731719/how-can-this-of-the-outer-class-be-accessed-from-an-inner-class

반응형