我有一些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;
}
}我想分享来自HasDurability类的代码与剑,但不是与项目。
编辑:我也想和其他职业分享HasDurability,比如装甲。
我只能扩展一个类。如何从Item和HasDurability到Sword类共享代码?
发布于 2020-05-23 05:15:28
看起来你更应该有这样的层次结构
public class Item
public class DurableItem extends Item
public class Sword extends DurableItem除非有一些东西可以具有持久性,而不是一个项目,这听起来不太可能。
发布于 2020-05-23 05:10:15
您可以通过组合或继承来重用代码。第一种方法是在“扩展”类中实例化一个要使用的方法的类,并像这样使用它。另一种方法是扩展类。所以要么你这么做
Item item = new Item(name, price, weight);
HasDurability hasDurability = new HasDurability(durability);在类中,您希望使用这些类,或者扩展一个公共超类。您可以创建一个抽象超类,并在需要时提供共享方法。
我还建议您将HasDurability类重命名为仅耐久性,因为"hasSomething“或"isSomething”通常用于布尔值,如:
boolean hasFur = false;// imagine you have an animal class and you wanna know if the animal has fur or nothttps://stackoverflow.com/questions/61963840
复制相似问题