简体   繁体   中英

Java: calling outer class method in anonymous inner class

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

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
        }
    }
}

当您声明匿名类时,内部范围会完全改变,虽然看起来您正在调用同一个对象,但引用在这里得到了更改,因此在处理匿名内部类/方法时,最好像稍后那样显式调用外部类实体

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM