【问题标题】:Can I access the "secondary this" from an inner class? [duplicate]我可以从内部类访问“辅助 this”吗? [复制]
【发布时间】:2016-12-30 16:14:33
【问题描述】:

我有基础课

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

从这些,我得出

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

InfantryAI 能否以某种方式获得 secondary(implicit) this 用于访问其周围类 Infantry 的成员?

具体来说,它需要确定其周围的类Infantry是否被其目标所针对,如下所示:

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

或者,通常是另一个Unit

【问题讨论】:

  • @SotiriosDelimanolis 对外部类的引用;我想我应该使用术语 outer this,而不是 secondary this
  • 封闭实例也可以。
  • @SotiriosDelimanolis 谢谢,我对正确的术语有点不清楚......我搜索了“从内部类访问”,但只找到了与成员访问相关的问题,而不是对象引用。

标签: java nested inner-classes derived-class


【解决方案1】:

您可以通过添加类名访问外部 this

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

这不适用于 static 嵌套类,因为它们不属于外部类的实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2014-07-17
    • 2011-02-13
    • 2011-08-11
    • 2014-09-09
    • 1970-01-01
    相关资源
    最近更新 更多