简体   繁体   English

从一个类中调用一个方法,该类是我的ArrayList的一个类的子类

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

I had attached the code in the end. 我在最后附加了代码。

So i have a class called Product, ComputerPart and Ram. 所以我有一个叫做Product,ComputerPart和Ram的类。 Ram extends Computer part , ComputerPart extends product from which all classes override price attribute since Product is an abstract class. Ram扩展Computer部件,ComputerPart扩展产品,由于Product是一个抽象类,因此所有类都从该产品覆盖价格属性。

Is my implementation of an ArrayList vs a List correct ? 我对ArrayList和List的实现正确吗? How do i reach a getter method in the ComputerParts class via the arraylist. 如何通过arraylist在ComputerParts类中达到getter方法。 I am a little confused on when i pass 76f though ComputerPart , how is it usable since it has not been properly instanciated 当我通过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>();

This is fine, though it is better practice to declare the variable type as the List interface (which makes your code more modular, since you can easily switch to a different List implementation) : 这很好,尽管将变量类型声明为List接口是一种更好的做法(这使您的代码更具模块化,因为您可以轻松地切换到其他List实现):

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

As for accessing specific properties of the objects stored in the list : 至于访问存储在列表中的对象的特定属性:

You can fetch the Product from the list : 您可以从列表中获取产品:

Product p = genericOrder.get(0);

Then you can check if it's a ComputerPart and cast it in order to access the specific methods of ComputerPart : 然后,您可以检查它是否是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