Java inheritance method with return type
•
Java
Is it correct to write such a course? The problem is the method getprice () in the item class Each item needs a getprice() But I can't actually reply to something So I fired this Getprice(), get the price of productitem Is there a stronger / better design 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; } }
Solution
It sounds like item should be an abstract class, and getprice () is 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 this:
Item item = new ProductItem("foo",10,2.0); double p = item.getPrice(); // 20.0
Each concrete (non Abstract) subclass you declare must override getprice () and provide an implementation
For details, see abstract classes and methods section of the java tutorial
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码