简体   繁体   English

Java:在匿名内部类中调用外部类方法

[英]Java: calling outer class method in anonymous inner class

Recently, I ran into a mysterious problem in an android project, which I described here .最近,我在一个android项目中遇到了一个神秘的问题,我在这里描述 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.假设我想在内部类中调用一个函数 foo() 。 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. PS:我在某处读到非静态内部类将始终包含外部类的实例。 So it will call outer function using that instance if I only use foo()?因此,如果我只使用 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
        }
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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