【发布时间】:2015-10-02 09:46:21
【问题描述】:
这样写我的课程是否正确?有问题的是Item 类中的方法getPrice()。每个项目都需要有一个getPrice()。但我实际上不能返回一些东西。所以我解雇了this.getPrice(),得到了ProductItem 的价格。有没有更可靠/设计更好的解决方案?
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中不存在。你只需要做return 0。被覆盖的类返回正确的东西,因为它是overriden
标签: java inheritance review