llm
llm

Reputation: 5669

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

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?
      }
    };
  }
}

Upvotes: 79

Views: 27454

Answers (5)

Josbert Lonnee
Josbert Lonnee

Reputation: 41

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

Upvotes: 1

Guillaume
Guillaume

Reputation: 14656

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

Outer.this

Upvotes: 113

OscarRyz
OscarRyz

Reputation: 199225

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.

Upvotes: 36

giri
giri

Reputation: 27199

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

Upvotes: 3

staticman
staticman

Reputation: 728

Prepend the outer class's class name to this:

outer.this

Upvotes: 10

Related Questions