类DiscountedItem extends 类Item。
类Item的内容:
- Java code
public class Item { double price; String name; public Item(String name, double price) { this.price = price; this.name = name; } public Item() {}}
类DiscountedItem的内容:
- Java code
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; }}
purchase类的内容:
- Java code
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()); }}
运行purchase的打印结果为0。而我期望的是结果是100(即10快 * 10个 = 100块钱)。
如何改Purchase类的getPrice()方法才能正确显示价格。
------解决方案--------------------
- Java code
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; }}
------解决方案--------------------
楼上正解。你用的变量时子类里面的,而父类的变量被你覆盖掉了。
------解决方案--------------------
也可以把
- Java code
return quantity * item.price;