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

发布于 2024-12-29 08:24:10 字数 627 浏览 3 评论 0原文

最近,我在一个android项目中遇到了一个神秘的问题,我描述了这里。我以某种方式解决了这个问题,但仍然不知道其背后的确切原因。

假设我想在内部类中调用函数 foo() 。 有什么区别

foo();

问题是,直接调用它或使用外部类实例调用它

OuterClass.this.foo();

此外,如果有人可以检查我的最后一个 与此相关的问题,并给我有关错误发生原因的线索。非常感谢。

PS:我在某处读到,非静态内部类将始终保存外部类的实例。那么如果我只使用 foo() ,它会使用该实例调用外部函数吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

归属感 2025-01-05 08:24:10

后者更明确,如果内部类中存在同名方法,则允许您调用外部类方法。

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 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
        }
    }
}
任性一次 2025-01-05 08:24:10

当您声明匿名类时,内部作用域完全改变,虽然看起来您正在调用相同的对象,但引用在此处发生变化,因此在处理匿名内部类/方法时,最好像稍后那样显式调用外部类实体

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文