首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java类之间共享公共代码

如何在Java类之间共享公共代码
EN

Stack Overflow用户
提问于 2020-05-23 05:03:08
回答 2查看 218关注 0票数 0

我有一些Java类:

代码语言:javascript
复制
public class Item {
    String name;
    int price;
    int weight;

    public Item(String name, int price, int weight) {
        this.name = name;
        this.price = price;
        this.weight = weight;
    }
}
代码语言:javascript
复制
public class Sword extends Item {
    int damage;
    int speed;

    public Sword(String name, int price, int weight, int damage, int speed) {
        super(name, price, weight);
        this.damage = damage;
        this.speed = speed;
    }
}
代码语言:javascript
复制
public class HasDurability {
    int current_durability;
    int max_durability;

    public HasDurability(int durability) {
        this.max_durability = durability;
        this.current_durability = durability;
    }

    public void damage(int damage) {
        current_durability -= damage;
    }
}

我想分享来自HasDurability类的代码与剑,但不是与项目。

编辑:我也想和其他职业分享HasDurability,比如装甲。

我只能扩展一个类。如何从Item和HasDurability到Sword类共享代码?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-23 05:15:28

看起来你更应该有这样的层次结构

代码语言:javascript
复制
public class Item

public class DurableItem extends Item

public class Sword extends DurableItem

除非有一些东西可以具有持久性,而不是一个项目,这听起来不太可能。

票数 0
EN

Stack Overflow用户

发布于 2020-05-23 05:10:15

您可以通过组合或继承来重用代码。第一种方法是在“扩展”类中实例化一个要使用的方法的类,并像这样使用它。另一种方法是扩展类。所以要么你这么做

代码语言:javascript
复制
Item item = new Item(name, price, weight);
HasDurability hasDurability = new HasDurability(durability);

在类中,您希望使用这些类,或者扩展一个公共超类。您可以创建一个抽象超类,并在需要时提供共享方法。

我还建议您将HasDurability类重命名为仅耐久性,因为"hasSomething“或"isSomething”通常用于布尔值,如:

代码语言:javascript
复制
boolean hasFur = false;// imagine you have an animal class and you wanna know if the animal has fur or not
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61963840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档