小编Luc*_*ani的帖子

具有返回类型的Java inherance方法

写这样的课程是否正确?在的问题是该方法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)

java inheritance review

3
推荐指数
1
解决办法
766
查看次数

标签 统计

inheritance ×1

java ×1

review ×1