首页 > 解决方案 > 每当实例化类时,如何实现该类的方法?

问题描述

我正在尝试编写一个基本的星球大战游戏。目前我有一堂课:

public class LightSaber extends SWEntity {

    public LightSaber(MessageRenderer m) {
        super(m);
        this.shortDescription = "A Lightsaber";
        this.longDescription = "A lightsaber.  Bzzz-whoosh!";
        this.hitpoints = 100000; // start with a nice powerful, sharp axe
        this.addAffordance(new Take(this, m));//add the take affordance so that the LightSaber can be taken by SWActors
    }

    public void canWield(SWActor actor) {
        if (actor.getForcepoints() >= minForcePoints) {
            this.capabilities.add(Capability.WEAPON);// it's a weapon. 
        }
    }

}

如果演员有足够的力量,基本上lightsaber就是一种武器。但是当我lightsaber像这样实例化类时:

LightSaber bensweapon = new LightSaber(m);
setItemCarried(bensweapon);

显然该canWield方法没有被调用。每次实例化类时如何调用该方法?我应该创建一个接口canWield并实现它吗?


编辑:好的,这是我的setItemCarried()代码:

public void setItemCarried(SWEntityInterface target) {
    this.itemCarried = target;
}

标签: javainheritance

解决方案


显然,某些SWEntityInterface(即LightSaber)对象不能被 some 使用SWActor。而且我猜您想在将其设置为携带物品之前检查是否this可以使用SWEntityInterface

您应该将该方法添加canWield(SWActor)SWEntityInterface并可选地提供返回的默认实现true

interface SWEntityInterface {
    boolean canWield(SWActor actor);
}

现在您将其称为setItemCarried

public void setItemCarried(SWEntityInterface target) {
    if (target.canWield(this)) {
        this.itemCarried = target;
    }
}

请注意,我们没有更改LightSaber初始化时发生的情况,因为创建LightSaber. 你在这里试图控制的是设置一个SWActor不能携带的东西作为它的itemCarried.

另外,考虑重命名canWieldcanBeWieldedBy.


推荐阅读