How can "this" of the outer class be accessed from an inner class?

JavaInner Classes

Java Problem Overview


Is it possible to get a reference to this from within a Java inner class?

i.e.

class Outer {

  void aMethod() {

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

Java Solutions


Solution 1 - Java

You can access the instance of the outer class like this:

Outer.this

Solution 2 - Java

Outer.this

ie.

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

BTW In Java class names start with uppercase by convention.

Solution 3 - Java

Prepend the outer class's class name to this:

outer.this

Solution 4 - Java

yes you can using outer class name with this. outer.this

Solution 5 - Java

Extra: It is not possible when the inner class is declared 'static'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionllmView Question on Stackoverflow
Solution 1 - JavaGuillaumeView Answer on Stackoverflow
Solution 2 - JavaOscarRyzView Answer on Stackoverflow
Solution 3 - JavastaticmanView Answer on Stackoverflow
Solution 4 - JavagiriView Answer on Stackoverflow
Solution 5 - JavaJosbert LonneeView Answer on Stackoverflow