Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving Ambiguity when Accessing Parent Class from Anonymous Class

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?

like image 883
Joseph Nields Avatar asked Mar 31 '15 14:03

Joseph Nields


2 Answers

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

like image 159
aioobe Avatar answered Nov 15 '22 23:11

aioobe


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

like image 43
swingMan Avatar answered Nov 15 '22 23:11

swingMan