我最后附上了代码。
所以我有一个名为 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 接口(interface)(这使您的代码更加模块化,因为您可以轻松切换到不同的 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());
}
关于java - 从一个类调用一个方法,该类是我创建了 ArrayList 的类的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26628935/