java - 每当实例化类时,如何实现该类的方法?
问题描述
我正在尝试编写一个基本的星球大战游戏。目前我有一堂课:
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;
}
解决方案
显然,某些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
.
另外,考虑重命名canWield
为canBeWieldedBy
.
推荐阅读
- javascript - 如何仅调用最近命中的 api 并在 react-native 中中止先前调用的 api 的会话?
- reactjs - react context vs redux vs hooks,应该考虑哪一个以及每个的不同之处
- laravel - 数据库播种这就是我们使用的原因
- docker - 使用 docker 文件在 Container 中挂载当前目录
- json - 获取在 EXEC() 中执行的动态 PIVOT 结果到 varchar 变量
- android - 当滚动达到高度的 20% 时折叠应用栏布局。我也想 snap 工作
- assembly - bootsect.s:我们如何在将代码本身移开后访问下一行?
- spring-boot - Spring boot 2.1.5、WebFlux、Reactor:如何正确处理MDC
- javascript - “payment_method_nonce”在 PHP 中返回一个空字符串
- c# - 并行修改 C# 对象列表中的属性