I have the following code
public class A extends Iterable<Integer> {
...
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
A a;
public boolean hasNext() {
...
}
public Integer next() {
...
}
public void remove(){
...
}
};
I would like to initialize the “a” field in the anonymous class with the instance of A that iterator method was called on. Is it possible?
Thank you.
You don’t need to.
You can call methods on the outer class normally within the inner class.
When you compile it, the compiler will automatically generate a hidden field that contains a reference to the outer class.
To reference this variable yourself, you can write
A.this. (A.thisis the compiler-generated field and is equivalent to yourafield)