寫這樣的類是否正確?有問題的是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