Java中, 一般來(lái)說(shuō)this指針指的是當(dāng)前正在訪(fǎng)問(wèn)的這段代碼的對(duì)象 ,但是如果在內(nèi)部類(lèi)中需要使用外部類(lèi)中的對(duì)象,這時(shí)就需要使用外部類(lèi)的類(lèi)名進(jìn)行限定。 這種方式在Android開(kāi)發(fā)中也比較常見(jiàn) 。
@Author: twlkyaopackage 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是內(nèi)部類(lèi),訪(fǎng)問(wèn)類(lèi)A中的outer()方法,又由于匿名內(nèi)部類(lèi)中有同樣的方法,所以需要使用A的this指針進(jìn)行限定。
輸出結(jié)果為:
inner runouter run--------outer run
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注