5

I recently ran into something like this...

public final class Foo<T>
implements Iterable<T> {

    //...

    public void remove(T t) { /* banana banana banana */ }

    //...

    public Iterator<T> Iterator {
        return new Iterator<T>() {

            //...

            @Override
            public void remove(T t) {
                // here, 'this' references our anonymous class...
                // 'remove' references this method...
                // so how can we access Foo's remove method?           
            }

            //...

        };
    }
}

Is there any way to do what I'm trying to while keeping this as an anonymous class? Or do we have to use an inner class or something else?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Joseph Nields
  • 5,527
  • 2
  • 32
  • 48
  • possible duplicate of [Getting hold of the outer class object from the inner class object](http://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object) – Raedwald Apr 02 '15 at 07:06

2 Answers2

9

To access remove in the enclosing class, you can use

...
    @Override
    public void remove(T t) {
        Foo.this.remove(t);         
    }
...

Related question: Getting hold of the outer class object from the inner class object

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
2

Foo.this.remove(t) will do the trick for you.

swingMan
  • 732
  • 1
  • 6
  • 17
  • 5
    There are already exactly the same answers. Please upvote them instead of posting a duplicate one. – Eel Lee Mar 31 '15 at 14:25