Java – how do I call methods for all objects in ArrayList?
So I have an interface, pet, as follows:
public interface Pet{ void Eat(); }
This is achieved by:
public class Puppies implements Pet { @Override public void Eat() { // Something gets eaten here,presumably } }
and
public class Kittens implements Pet { @Override public void Eat() { // Everybody kNows Kittens eats something different } }
I hope what I need to do next is to create an ArrayList for a new pet:
public class PetList{ public PetList(){ ArrayList pets = new ArrayList<Pet>(); Puppies spot = new Puppies(); Puppies rex = new Puppies(); Kittens meowth = new Kittens(); pets.add(spot); pets.add(rex); pets.add(meowth); } public static void main(String[] args){ // No idea how to handle this bit }
The next thing I have to do is tell all my pets to eat What shall I do?
Solution
The main problem with the current code is that ArrayList (pets) is a local problem of the petlist constructor, which means that you cannot access the constructor outside the class petlist
Therefore, first, use ArrayList as an instance variable of the petlist class so that it can be accessed through an object even outside the constructor
Then, you can provide an eatall () method that iterates over ArrayList < pet > and calls the eat () method on all pet objects
You can refer to the following code and follow the inline comments:
public class PetList{ private List<Pet> pets;//Now this is an instance variable public PetList(){ this.pets = new ArrayList<Pet>();//this list is not local Now Puppies spot = new Puppies(); Puppies rex = new Puppies(); Kittens meowth = new Kittens(); pets.add(spot); pets.add(rex); pets.add(meowth); } public void eatAll() { //method to invoke eat() on list of pets for(Pet pet : this.pets) { //iterate the pets list pet.eat();//call eat() on each pet object } } public static void main(String[] args){ PetList petList = new PetList(); petList.eatAll();//invoke the eatAll() method } }
As a side note, I strongly recommend that you follow the Java Naming standard (eat () should be eat (), that is, the method name should start with lowercase) and consider renaming the petlist class to petstesting (or something), so that it will be more intuitive for developers
Finally, but it is important not to assign objects directly to specific class types, such as ArrayList < pet > pets = new ArrayList < > (); Or puppy spots = new puppy ()
The best practice is that you need to assign objects to the interface type list < pet > pets = new ArrayList < pet > (); Or pet spot = new purchases(); (code called interface type)