3

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.

Stefan Stanković
  • 628
  • 2
  • 6
  • 17

1 Answers1

6

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
tkausl
  • 13,686
  • 2
  • 33
  • 50