Java的:调用匿名内部类外部类的方法 [英] Java: calling outer class method in anonymous inner class

查看:822
本文介绍了Java的:调用匿名内部类外部类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我遇到了一个神秘的问题在Android项目,这是我所描述的here.我莫名其妙地解决了这个问题,但还是不知道它背后的确切原因。

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.

比方说我要调用一个函数foo()中的内部类。现在的问题是,什么叫直接像

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

此外,我将AP preciate如果任何人都可以查看我的最后<一href="http://stackoverflow.com/questions/9039017/android-app-application-cannot-be-instantiated-due-to-nullpointerexception/9039931">question与此相关的,并给我提供一些有关为何发生错误的线索。非常感谢。

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:我读的地方,非静态内部类总是拥有外部类的一个实例。因此,它会调用外部函数使用举例来说,如果我只用富()?

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

这篇关于Java的:调用匿名内部类外部类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆