繁体   English   中英

如何跨 Java 类共享通用代码

[英]How to share common code across Java classes

我有那些 Java 类:

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

我想与 Sword 共享来自 HasDurability class 的代码,但不与 Item 共享代码。

编辑:我还想与 Armor 等其他类共享 HasDurability。

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

您可以按如下方式使用组合:

public class Sword extends Item {
    int damage;
    int speed;
    HasDurability obj;
    //...
}

您可以通过组合或 inheritance 重用代码。 第一种方法是您实例化一个 class 您想使用“扩展” class 中的方法,然后像这样使用它。 另一种方法是扩展 class。 所以要么你做

Item item = new Item(name, price, weight);
HasDurability hasDurability = new HasDurability(durability);

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

我还建议您将 HasDurability class 重命名为 Durability,因为“hasSomething”或“isSomething”通常用于 boolean 值,例如:

boolean hasFur = false;// imagine you have an animal class and you wanna know if the animal has fur or not

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

public class Item

public class DurableItem extends Item

public class Sword extends DurableItem

除非有什么东西可以拥有不是物品的耐用性,这听起来不太可能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM