20

Recently, I ran into a mysterious problem in an android project, which I described here. I somehow solved the problem, but still don't know the exact reason behind it.

Let's say I want to call a function foo() in the inner class. The question is, what's the difference between calling it directly like

foo();

or calling it with the outer class instance

OuterClass.this.foo();

Besides, i will appreciate if anyone can check my last question related to this, and give me a clue about why the error occurs. Many thanks.

PS: I read somewhere that the non-static inner class will always hold an instance of the outer class. So it will call outer function using that instance if I only use foo()?

Community
  • 1
  • 1
Selkie
  • 1,773
  • 1
  • 14
  • 21

2 Answers2

26

The latter is more explicit and will allow you to call the outer class method if one exists in the inner class with the same name.

class OuterClass {
    void foo() { System.out.println("Outer foo"); }

    View.OnClickListener mListener1 = new View.OnClickListener() {
        void foo() { System.out.println("Inner foo"); }

        @Override public void onClick(View view) {
            foo(); //Calls inner foo
            OuterClass.this.foo(); //Calls outer foo
        }
    }

    View.OnClickListener mListener2 = new View.OnClickListener() {
        @Override public void onClick(View view) {
            foo(); //Calls outer foo
            OuterClass.this.foo(); //Calls outer foo
        }
    }
}
Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • Thx. But I'm sure the inner class doesn't have a function with the same name in my case. Is there any other specific difference except the explicit part? – Selkie Jan 28 '12 at 06:28
  • Not in this context. I looked at your sources question and the fact that the change you made solved it is inexplicable. That should not have effected it at all. Doing this is purely to clear up any ambiguities in what you are referring to... – Jake Wharton Jan 28 '12 at 06:34
  • you r right. I made a mistake in there. Thank for the enlightening! – Selkie Jan 28 '12 at 15:15
0

When you declare anonymous class, inner scope changes completely and though it look like you are calling same object but reference get changes here and hence it while dealing with anonymous inner class/method it is better to call outer class entities explicitly as you did laterl