Stefan Stanković Stefan Stanković - 3 months ago 6
Java Question

Can I access the "secondary this" from an inner class?

I have basic classes

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


From these, I have derived

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


Can the class
InfantryAI
somehow get the secondary(implicit)
this
that is used for accessing the members of it's surrounding class
Infantry
?


Specifically, it needs to determine if its surrounding class
Infantry
is being targetted by its target, like this:

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


or, generally, by another
Unit
.

Answer

You can access the outer this by prepending the classname:

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

This doesn't work with static nested classes though as they don't belong to a instance of the outer class.