![](/img/trans.png)
[英]How to add an object from an ArrayList to another ArrayList in another class
[英]How to add an a class to an ArrayList in another class?
我創建了一個程序,該程序包括一個名為“ Appliance”的超類 ,從該類我可以得到諸如“ ElectricCooker”的子類。 我需要知道創建一個將所有這些設備存儲在另一個類中的ArrayList。 我對如何做到這一點有些困惑。 到目前為止,這是我所做的:
ArrayList<Appliance> applianceList = new ArrayList<>();
ElectricShower a = new ElectricShower(0,0,0,0);
public void addAppliance()
{
applianceList.add(a);
}
這是實現此目標的正確方法嗎? 任何幫助表示贊賞,謝謝。
您可能需要復習繼承和多態性的概念。 這應該可以完成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);
}
}
用法示例:
AnotherClass another = new AnotherClass();
ElectricShower shower = new ElectricShower();
another.addAppliance(shower);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.