java - 如何在 Java 类之间共享公共(public)代码

标签 java

我有那些 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 类的代码,但不与 Item 共享。

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

我只能延长一个类。如何将 Item 和 HasDurability 的代码共享到 Sword 类?

最佳答案

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

public class Item

public class DurableItem extends Item

public class Sword extends DurableItem

除非有某种东西可以具有耐用性,但它不是元素,这听起来不太可能。

关于java - 如何在 Java 类之间共享公共(public)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61963840/

相关文章:

java - findbug 与 RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT 的奇怪行为

java - 单元测试 jsf 2.0 Managed Bean 的最佳方式

java - void cv::cvtColor(cv::InputArray Android) 断言失败(scn == 3 || scn == 4)

java - SWT 表中列的宽度

java - 解释用Java创建金字塔

java - 如何获取捕获的图像的URL?

java - 20 个模拟用户的 Hibernate 死锁

java - 如何从 LinkedHashMap 迭代器获取键值对?

java - 使用 Java 对不同时间间隔的时间条目进行求和和分类

java - 当 RAD 执行 "Run On Server"时,WebSphere 将 EAR 文件放在哪里?以及如何在其上运行createEJBStubs?