簡體   English   中英

從一個類中調用一個方法,該類是我的ArrayList的一個類的子類

[英]Calling a method from a class that is a subclass of a class of which i have made an ArrayList of

我在最后附加了代碼。

所以我有一個叫做Product,ComputerPart和Ram的類。 Ram擴展Computer部件,ComputerPart擴展產品,由於Product是一個抽象類,因此所有類都從該產品覆蓋價格屬性。

我對ArrayList和List的實現正確嗎? 如何通過arraylist在ComputerParts類中達到getter方法。 當我通過ComputerPart通過76f時,我有些困惑,因為它沒有被正確地實例化,所以如何使用?

abstract class Product {
    protected float price;
    public static int i =0;                   // to keep count starts at zero 
    protected static int ID ;               // to update and keep track of ID even if i changes 

     // return the price of a particular product
    abstract float price();
}


class ComputerPart extends Product {

     public ComputerPart(float p) {
        i += 1;                             // each time constructor invoked ,  
        ID = i ;                                // to update ID even if i changes.    
        price = p;
    }

    public float price() { return price; }

    public static String getID(){   // a getter method so ID can be nicely formated and returned
        String Identification =  "ID#" + ID;
        return Identification;
    }
}

public abstract class GenericOrder {

    public static void main(String[] args) {

        ArrayList<Product> genericOrder= new ArrayList<Product>();
        genericOrder.add(new ComputerPart(76f));
    }
}
ArrayList<Product> genericOrder= new ArrayList<Product>();

這很好,盡管將變量類型聲明為List接口是一種更好的做法(這使您的代碼更具模塊化,因為您可以輕松地切換到其他List實現):

List<Product> genericOrder= new ArrayList<Product>();

至於訪問存儲在列表中的對象的特定屬性:

您可以從列表中獲取產品:

Product p = genericOrder.get(0);

然后,您可以檢查它是否是ComputerPart並進行強制轉換以訪問ComputerPart的特定方法:

if (p instanceof ComputerPart) {
    ComputerPart c = (ComputerPart) p;
    System.out.prinln(c.price());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM