I've created a program includes a super class called "Appliance" , from this I have sub classes such as "ElectricCooker" . I need to know create an ArrayList that stores all of these Appliances in another class. 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:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.