Is it correct to write my classes like this? In question is the method getPrice()
in the Item
class. Every Item needs to have a getPrice()
. But I can't actually return something. So I fire the this.getPrice()
with gets me the Price of the ProductItem
. Is there a more solid / better designed solution?
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;
}
}
It sounds like Item
should be an abstract class then, with getPrice()
being an abstract method:
public abstract class Item {
private final String description;
public Item(String description) {
this.description = description;
}
public abstract double getPrice();
public String getDescription() {
return description;
}
}
That means you won't be able to write
Item item = new Item("foo"); // Invalid, because Item is abstract
But you can write:
Item item = new ProductItem("foo", 10, 2.0);
double p = item.getPrice(); // 20.0
Every concrete (non-abstract) subclass you declare will have to override getPrice()
and provide an implementation.
See the abstract classes and methods section of the Java tutorial for more details.
See more on this question at Stackoverflow