簡體   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