繁体   English   中英

Java ArrayList 向下铸造

[英]Java ArrayList Downcasting

所以我一直在从事一个项目,我需要一个列表来填充它的新子 class 对象。

我用传统方法做到了,其中一个 ArrayList 将填充一种子 Class。 But to make the code shorter and more efficient, I'm considering to downcast the ArrayList to have a single ArrayList of parent class that have both of it's child classes object inside it. 可能吗?

这些是事物的父 class

 package Model;

public class Things {
    protected String id;
    protected String name;
    protected double price;
    protected int stock;
    protected int bought;

public Things() {}

public Things(String id, String name, double price, int stock) {
    this.id = id;
    this.price = price;
    this.name = name;
    this.stock = stock;
}

public String getId() {
    return id;
}

public String getName() {
    return name;
}

public double getPrice() {
    return price;
}

public int getStock() {
    return stock;
}

public void minusStock(int bought) {
    this.stock = stock - bought;
 }
}

这些是手机和优惠券的子 class

手机小孩class

package Model;

public class Handphone extends Things {
    private String color;

    public Handphone(String id, String name, double price, int stock, String color) {
        super(id, name, price, stock);
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

代金券子class

package Model;

public class Voucher extends Things {
    private double tax;

    public Voucher(String id, String name, double price, int stock, double tax) {
        super(id, name, price, stock);
        this.tax = tax;
    }

    public double getTax() {
        return tax;
    }

    public double getsellingPrice() {
        return (price + (price*tax));
    }
}

因此要提到主菜单界面会在不同的package上,我把import Model.*放在上面。 如果我这样说,它是否也会包含在菜单 package 中?

您可以将HandphoneVoucher放入List<Things>Thing可能是更合适的名称?),无需强制转换:

List<Things> things = new ArrayList<>();
things.add(new Handphone("id", "name", 1, 1, "color"));

但是,如果您访问该列表并且确实需要知道它是Handphone还是Voucher ,您将不得不向下转换 object。

这种类型的铸造可能是设计缺陷的标志,因此请仔细考虑您的解决方案。

如果您将一个包含 class 本身的protected吸气剂字段包含到您的父 class 中,则可以在运行时知道它是耳机、凭证还是其他东西。

不过,正如@Maglinex 建议的那样,请确保您没有看到设计缺陷。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM