From an inner class, "this" points to the inner object. How do I get a "this" pointer to the enclosing object?

Alex Chaffee

Refer to the outer object by class name: Outer.this, in the following example.

class Outer {
    int x = 5;
    class Inner {
        int x = 10;
        public void test() {
            System.out.println( Outer.this.x );
        }
    }
    public void test() {
        new Inner().test();
    }
}                      
Calling new Outer().test() prints "5".

This is not a very useful example, but sometimes you may want to, e.g., register the outer class as a listener, for which you need a "this" pointer.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact