【发布时间】:2018-04-23 04:00:17
【问题描述】:
我的目标是创建一个超类产品
用这个超类创建不同的对象,例如:
- USB 记忆棒 8gb
- HHD 1tb
- SSD 512gb
都具有不同的价值(如价格)。
还有一个子类来创建这些产品的不同对象(例如 USB 记忆棒 8gb:我总共有 5 个(对象):1. 新的,2. 使用过的, 3. 二手,4. 新,5. 新)
对于我的版本(见上文),您总是需要为每个版本 (1-5) 提供相同的参数
Item usbstick1;
usbstick1 = new Item(50, "3.0 USB-Stick with 8 Gigybytes of storage", true)
如何实现:
a) 每次创建新的子类对象时,只引用已创建的“产品”(如 USB Stick 8gb)?
b) 我如何将此参考用于不同的子类?
如果我有这个超类
public class Product {
double price
String description
public Item(double price, String description) {
setPrice(price);
setDescription(descrition);
}
setPrice(double newPrice) {
price=newPrice;
}
public void setDescription(String newDescription) {
description=newDescription;
}
这个子类
public class Item extends Product {
boolean sealed;
public Item(double price, String description, boolean sealed) {
super(price, description);
setSealed(sealed);
}
public void setSealed(newSealed) {
sealed=newSealed;
}
Aa 以及这个 子类
public class UsedItem extends Product {
int usedDays;
public UsedItem(double price, String description, int usedDays) {
super(price, description);
setUsedDays(usedDays);
}
public void setUsedDays(newUsedDays) {
usedDays=newUsedDays;
}
【问题讨论】:
标签: java object inheritance polymorphism