215

In the following snippet:

public class a {
    public void otherMethod(){}
    public void doStuff(String str, InnerClass b){}
    public void method(a){
        doStuff("asd",
            new InnerClass(){
                public void innerMethod(){
                    otherMethod();
                }
            }
        );
    }
}

Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is outer.otherMethod(), or something of the like, but can't seem to find anything.

spongebob
  • 8,370
  • 15
  • 50
  • 83
shsteimer
  • 28,436
  • 30
  • 79
  • 95

2 Answers2

365

In general you use OuterClassName.this to refer to the enclosing instance of the outer class.

In your example that would be a.this.otherMethod()

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 1
    can you tell why `a.otherMethod()` wont work? – T.Todua Jan 17 '17 at 09:28
  • 3
    @T.Todua `OuterClassName.otherMethod()` would refer to a static method, so you need `OuterClassName.this` to get the instance of the outer class. – Bill the Lizard Jan 17 '17 at 15:00
  • 1
    Can OuterClassName.this be null inside an inner class, in some case? – Apurv Gupta Feb 06 '17 at 12:41
  • 1
    @ApurvGupta I don't think so. Only possibility would have been if you had tried to create an anonymous inner class from static method. But if you try to use "a.this" in that case, you will get a compiler error. – rents Apr 16 '17 at 21:03
48
OuterClassName.this.outerClassMethod();
jjnguy
  • 136,852
  • 53
  • 295
  • 323