Java中, 一般来说this指针指的是当前正在访问的这段代码的对象 ,但是如果在内部类中需要使用外部类中的对象,这时就需要使用外部类的类名进行限定。 这种方式在Android开发中也比较常见 。
@Author: twlkyao
package twlkyao;
public class A {
public A() {
Inner inner = new Inner();
inner.outer(); // call the inner class\'s outer method.
this.outer(); // call A\'s outer method.
}
public void outer() {
System.out.println(\"outer run\");
}
class Inner {
public void outer(){
System.out.println(\"inner run\");
A.this.outer(); // call A\'s outer method.
System.out.println(\"--------\");
}
}
public static void main(String[] args) {
A a = new A();
}
}
Inner是内部类,访问类A中的outer()方法,又由于匿名内部类中有同样的方法,所以需要使用A的this指针进行限定。
输出结果为:
inner run outer run -------- outer run
本文地址:https://www.stayed.cn/item/4153
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我