写这样的类是否正确?有问题的是Item
类中的方法getPrice()
。每个项目需要有一个getPrice()
。但我实际上不能回报什么。所以我发射this.getPrice()
让我的价格ProductItem
。是否有更坚实/更好设计的解决方案?返回类型的Java Inherance方法
class Item {
String description;
public Item(String description) {
this.description = description;
}
double getPrice(){return this.getPrice();} //TODO Correct like this?
}
class ProductItem extends Item {
int amount;
double pricePerUnit;
public ProductItem(String description, int amount, double pricePerUnit) {
super(description);
this.amount = amount;
this.pricePerUnit = pricePerUnit;
}
@Override
double getPrice(){
return amount * pricePerUnit;
}
}
'this.getPrice()'在'Item'中不存在。你只需要做'返回0'。覆盖类返回正确的东西,因为它是“覆盖” – kevintjuh93