Disambiguating access to the parent class from an anonymous class

I recently came across 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 remove method? } //... }; } } 

Is there a way to do what I'm trying to keep as an anonymous class? Or do we need to use an inner class or something else?

+5
source share
3 answers

To access remove in the inclusion class, you can use

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

Related question: Getting an external class object from an internal class object

+9
source

You can access the closing class using Classname.this . So in your example:

 public void remove(T t){ Foo.this.remove(t); } 
+7
source

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

+2
source

Source: https://habr.com/ru/post/1216541/


All Articles