150

Given the following code:

public interface Selectable {
  public void select();
}

public class Container implements Selectable {
  public void select() {
  ...
  }
  public void createAnonymousClass() {
    Selectable s = new Selectable() {
      public void select() {
        //see comment below.
      }
    };
  }
}

I want to access Container.select() from within my anonymous class' select() method. However, this.select() would again call the anonymous class' select() method.

My suggestion would be:

Introduce a field into Container, e.g.

private Container self = this;

Now I can access Container.select() by calling self.select() from within the anonymous class.

Is this a reasonable way? Or are there any better ways?

2 Answers 2

286
Container.this.select();
4
  • 3
    I didn't know even this keywords could be differentiated just as methods and attributes can. +1 Commented Jun 6, 2016 at 6:50
  • It should be noted that you have to specify Exactly Container class here. Any of its ancestors won't be accepted.
    – velis
    Commented Dec 9, 2017 at 13:34
  • save my... night, maybe ? +1
    – Gianmarco
    Commented Nov 16, 2020 at 23:25
  • what if we try it for the same named an anonymous class and a confidential class? (Supposed not implementing an interface.)
    – wolfenblut
    Commented Mar 30, 2023 at 13:11
44

You can write Container.this.select() to distinct from the inner class !

Not the answer you're looking for? Browse other questions tagged or ask your own question.