日期:2014-05-20 浏览次数:20818 次
public class Item { double price; String name; public Item(String name, double price) { this.price = price; this.name = name; } public Item() {} }
public class DiscountedItem extends Item { String name; double price; int bulkQuen; double bulkPri; public DiscountedItem(String name, double price, int bulkQuen, double bulkPri) { this.name = name; this.price = price; this.bulkQuen = bulkQuen; this.bulkPri = bulkPri; } }
public class Purchase { Item item; int quantity; public Purchase(Item item, int quantity) { this.item = item; this.quantity = quantity; } public double getPrice() { return quantity * item.price; } public static void main(String[] args) { DiscountedItem di = new DiscountedItem("apple", 10, 20, 7); Purchase p = new Purchase(di, 10); System.out.println(p.getPrice()); } }
public class DiscountedItem extends Item { int bulkQuen; double bulkPri; public DiscountedItem(String name, double price, int bulkQuen, double bulkPri) { super(name,price); this.bulkQuen = bulkQuen; this.bulkPri = bulkPri; } }
------解决方案--------------------
楼上正解。你用的变量时子类里面的,而父类的变量被你覆盖掉了。
------解决方案--------------------
也可以把
return quantity * item.price;