Java 如何在实例化该类时实现该类的方法?
我正在编写一个基本的星球大战游戏。目前我有一门课:Java 如何在实例化该类时实现该类的方法?,java,inheritance,Java,Inheritance,我正在编写一个基本的星球大战游戏。目前我有一门课: public class LightSaber extends SWEntity { public LightSaber(MessageRenderer m) { super(m); this.shortDescription = "A Lightsaber"; this.longDescription = "A lightsaber. Bzzz-whoosh!"; t
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 bensweapon = new LightSaber(m);
setItemCarried(bensweapon);
显然,canwiver
方法没有被调用。每次实例化类时如何调用该方法?我应该创建一个接口canwilve
并实现它吗
编辑:好的,这是我的
setItemCarried()
代码:
public void setItemCarried(SWEntityInterface target) {
this.itemCarried = target;
}
显然,一些
SWEntityInterface
(即LightSaber
)对象不能被一些SWActor
使用。我想你应该先检查这个
是否可以使用SWEntityInterface
,然后再将其设置为所携带的物品
您应该将方法canwiver(SWActor)
添加到SWEntityInterface
中,并可以选择提供返回true
的默认实现
interface SWEntityInterface {
boolean canWield(SWActor actor);
}
现在您在setItemCarriered
中调用它:
public void setItemCarried(SWEntityInterface target) {
if (target.canWield(this)) {
this.itemCarried = target;
}
}
请注意,我们没有更改初始化LightSaber
时发生的情况,因为创建LightSaber
的实例完全可以。这里您试图控制的是将SWActor
无法携带的内容设置为其itemCarried
也可以考虑重命名<代码> CANWELD 到<代码> CabBeWeldE/<代码>。< /P>未实现“为什么”?在光剑类中,该方法似乎implemented@azro我认为OP的意思是“调用”。给出
setItemCarried()
的代码,在其中添加一些东西来添加setItemCarried代码当您创建LightSaber
的新实例时,您需要一个参与者来调用该方法。在构造函数中创建一个actor,或者将其作为参数传递给LightSaber
,然后调用它,否则,如果传递null
或尝试在没有任何参数的情况下调用,则它将不起作用。