【问题标题】:Use a superclass instance with subclass instances将超类实例与子类实例一起使用
【发布时间】: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


    【解决方案1】:

    您可能需要考虑将 UsedItem 类更改为拥有 Product 的实例,而不是扩展它,然后在构造函数中传递一个产品:

    public class UsedItem {
    
       Product product;
       int usedDays;
    
       public UsedItem(Product product) {
           this.product = product;
       }
    
       public void setUsedDays(newUsedDays) {
           usedDays=newUsedDays;
       }
    }
    

    然后要创建新的UsedItems,您只需将您创建的相同产品实例传递给它:

    Item usbstick;
    usbstick = new Item(50, "3.0 USB-Stick with 8 Gigybytes of storage", true);
    
    UsedItem usb1 =  new UsedItem(usbstick);
    UsedItem usb2 =  new UsedItem(usbstick);
    UsedItem usb3 =  new UsedItem(usbstick);
    

    或者,您可以将使用过的项目设置为在构造函数中获取项目并从中设置值:

    public class UsedItem extends Item{
    
       public UsedItem(Product product) {
           super(product.price, product.description);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      相关资源
      最近更新 更多