具有返回类型的Java inherance方法
发布时间:2020-12-15 05:18:18 所属栏目:Java 来源:网络整理
导读:写这样的课程是否正确?问题是Item类中的方法getPrice().每个Item都需要一个getPrice().但我实际上无法回复一些东西.所以我解雇了this.getPrice(),得到了ProductItem的价格.是否有更坚固/更好的设计解决方案? class Item { String description; public Item
写这样的课程是否正确?问题是Item类中的方法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()并提供实现. 有关详细信息,请参阅abstract classes and methods section of the Java tutorial. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |