如何在实例化类时如何实现该类的方法?

时间:2018-05-12 16:20:40

标签: java inheritance

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

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;
}

1 个答案:

答案 0 :(得分:3)

显然,某些SWEntityInterface无法使用某些LightSaber(即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重命名为@Entity (name = "trackers") public class Tracker implements Serializable, Comparable<Tracker> { @Id @GeneratedValue private Integer id; @Column private String number; @Column (name = "devID") private String devID; @Column (name ="creationtimestamp") private long creationTimestamp; @Column private double lon; @Column private double lat; public Tracker() { this.creationTimestamp = System.currentTimeMillis(); } @Override public int compareTo(Tracker that) { return Long.compare(this.creationTimestamp, that.creationTimestamp); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getDevID() { return devID; } public void setDevID(String devID) { this.devID = devID; } public long getCreationTimestamp() { return creationTimestamp; } public void setCreationTimestamp(long creationTimestamp) { this.creationTimestamp = creationTimestamp; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } }