-2

Lately I've found out that this works, although I'd expect it not to:

class Outer
{ 
    Button b;

    void foo() {}


    void bar()
    {
        b = new Button();
        b.setOnClickListener(new OnClickListener(){
            @Override
            public void OnClick()
            {
               foo();
            }
        }); 
    }
}

I'd expect Outer.this.foo() to be required, but seems that simply foo() also works. Could someone tell me when exactly this was added to the language? Please help me understand exact name resolution rules here. Thanks!

The questions:

1) Why is this working?

2) If this works, why do we need the "Outer.this" syntax?

Alex Jenter
  • 4,324
  • 4
  • 36
  • 61

1 Answers1

2

The possibility to call methods like this has existed since the inner classes had been introduced. The mechanism for resolving the instance that a method is called on is described in detail in Java Language Specification, Section 15.12.4.1., Compute Target Reference (If Necessary).

You are probably refering to the fact that you don't need the "Qualified this". But this this is mainly intended to resolve ambiguities when the inner instance and the outer instance have a method with the same signature.

Marco13
  • 53,703
  • 9
  • 80
  • 159