我有那些 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/