Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: calling outer class method in anonymous inner class

Tags:

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()?

like image 255
Selkie Avatar asked Jan 28 '12 05:01

Selkie


People also ask

Can inner class calling Outer method?

No, you cannot assume that the outer class holds an instance of the inner class; but that's irrelevant to the question. You're first question (whether the inner class holds an instance of the outer class) was the relevant question; but the answer is yes, always.

Can an inner class access outer class methods?

Any non-static nested class is known as inner class in java. Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.

Can inner class access outer class private methods Java?

Inner classes can even access the private variables/methods of outer classes.

Can inner classes access outer class private members?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.


1 Answers

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
        }
    }
}
like image 64
Jake Wharton Avatar answered Oct 06 '22 00:10

Jake Wharton