这样写我的课程是否正确?在的问题是该方法getPrice()
的Item
类。每个项目都需要有一个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;
}
}
听起来Item
应该是一个抽象类,然后getPrice()
是一个抽象方法:
public abstract class Item {
private final String description;
public Item(String description) {
this.description = description;
}
public abstract double getPrice();
public String getDescription() {
return description;
}
}
这意味着您将无法写
Item item = new Item("foo"); // Invalid, because Item is abstract
但是你可以这样写:
Item item = new ProductItem("foo", 10, 2.0);
double p = item.getPrice(); // 20.0
您声明的每个具体(非抽象)子类都必须重写getPrice()
并提供实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句