java调用内部类的方法调用,Java的:调用匿名内部类外部类的方法

本文探讨了在Android项目中遇到的一个神秘问题,涉及内部类调用外部类方法的不同方式。作者发现直接调用foo()与使用OuterClass.this.foo()存在差异,后者更明确,尤其当内外类有同名方法时。内部类会持有外部类实例,因此不加限定符可能调用到内部的方法。同时,文章请求读者帮助分析相关错误原因。
摘要由CSDN通过智能技术生成

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值