[英]How to add an a class to an ArrayList in another class?
I've created a program includes a super class called "Appliance" , from this I have sub classes such as "ElectricCooker" . 我创建了一个程序,该程序包括一个名为“ Appliance”的超类 ,从该类我可以得到诸如“ ElectricCooker”的子类。 I need to know create an ArrayList that stores all of these Appliances in another class.
我需要知道创建一个将所有这些设备存储在另一个类中的ArrayList。 I'm a little confused on how to accomplish this.
我对如何做到这一点有些困惑。 This is what I have done so far:
到目前为止,这是我所做的:
ArrayList<Appliance> applianceList = new ArrayList<>();
ElectricShower a = new ElectricShower(0,0,0,0);
public void addAppliance()
{
applianceList.add(a);
}
Is this the correct way to implement this? 这是实现此目标的正确方法吗? Any help is appreciated, thanks.
任何帮助表示赞赏,谢谢。
You might be needing to review the concepts of Inheritance and Polymorphism . 您可能需要复习继承和多态性的概念。 This should accomplish what you want in Java:
这应该可以完成Java所需的工作:
public class Appliance {
// Appliance definition goes in here
}
public class ElectricShower extends Appliance {
// ElectricShower definition goes in here
}
public class AnotherClass {
ArrayList<Appliance> appliances = new ArrayList<Appliance>();
public void addAppliance(Appliance appliance) {
this.appliances.add(appliance);
}
}
Example usage: 用法示例:
AnotherClass another = new AnotherClass();
ElectricShower shower = new ElectricShower();
another.addAppliance(shower);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.