【问题标题】:Java ArrayList DowncastingJava ArrayList 向下转换
【发布时间】:2020-07-28 01:23:58
【问题描述】:

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

我已经用传统方法实现了,一个 ArrayList 将填充一种子类。但是为了使代码更短更高效,我正在考虑将 ArrayList 向下转换为有一个父类的 ArrayList,其中有两个子类对象。有可能吗?

这些是Things的父类

 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;
 }
}

这些是它的子类 Handphone and Vouchers

手机子类

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;
    }
}

凭证子类

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));
    }
}

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

【问题讨论】:

    标签: java oop arraylist downcast upcasting


    【解决方案1】:

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

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

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

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

    【讨论】:

    • List和ArrayList有什么区别?我可能会漏掉什么样的设计缺陷?
    • List 是接口。 ArrayListList 的一种类型(可能是最常见的),它在内部由数组支持。
    • @DeanDebrio 你没有展示足够的代码,只展示了三个常规类。我认为这个问题最好保持原样。您有codereview.stackexchange.com,您可以在其中提出有关如何改进代码的问题。
    • 是的,因为我的代码没有那么复杂,所以我没有考虑过审查它以改进设计。我只是想知道,因为虽然铸造一个物体是一种额外的工作,但如果它以设计缺陷为代价,为什么他们首先要制造它。不过谢谢你的建议,我会考虑的。
    【解决方案2】:

    如果您在父类中包含一个带有protected getter 的字段,该字段包含该类本身,那么在运行时就可以知道它是耳机、凭证还是其他东西。

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

    【讨论】:

    • 这是否意味着如果铸造过程已经被继承,则根本不需要?
    • 强制转换仍然是必要的,但是您的 List 的使用者只需调用一个 getter 方法就知道要将 Things 转换成什么。类型擦除在这里得到了很好的解释:baeldung.com/java-type-erasure
    • 您能否提供那个“受保护的吸气剂”示例?看起来我需要它从 ArrayList 中获取特定对象
    猜你喜欢
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多