具有返回类型的Java inherance方法

Luc*_*ani 3 java inheritance review

写这样的课程是否正确?在的问题是该方法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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 13

听起来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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这意味着你将无法写作

Item item = new Item("foo"); // Invalid, because Item is abstract
Run Code Online (Sandbox Code Playgroud)

但你可以这样写:

Item item = new ProductItem("foo", 10, 2.0);
double p = item.getPrice(); // 20.0
Run Code Online (Sandbox Code Playgroud)

您声明的每个具体(非抽象)子类都必须覆盖getPrice()并提供实现.

有关更多详细信息,请参阅Java教程抽象类和方法部分.