2016-08-23 54 views
3

我有基本的類我可以從內部課程訪問「輔助這個」嗎?

abstract class Unit { 
    Unit target; 
    abstract class UnitAI {/*...*/} 
} 

從這些,我已經得出

class Infantry extends Unit { 
    class InfantryAI extends UnitAI {/*...*/} 
} 

InfantryAI能以某種方式獲取二次隱含this是用於訪問成員它的周圍類Infantry

具體而言,需要確定其周圍類Infantry是以它的目標爲對象,像這樣:

if (/*secondary_this.*/target.target == secondary_this) 

或,一般地,由另一Unit

+0

@SotiriosDelimanolis對外部類的參照;我想我應該使用術語* outer *'this',而不是* secondary *'this'。 –

+1

_Enclosing instance_也可以工作。 –

+0

@SotiriosDelimanolis謝謝,我對正確的術語有點不清楚......我搜索「從內部類訪問」,但只發現與成員訪問相關的問題,而不是對象引用。 –

回答

6

您可以通過在前面加上類名訪問this

Infantry.this.target; //"this" of the Infantry class from inside InfantryAI 
Unit.this.target; //"this" of the Unit class from inside UnitAI 

這不會static嵌套類,雖然他們不屬於外部類的一個實例工作。

相關問題