So I have an interface Pet
shown below:
public interface Pet{
void Eat();
}
Which is implemented 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
}
}
Hopefully, what I've done next is create an ArrayList
of new pets:
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
}
What I want to do next is go through and tell all my pets to eat. How would I do this?
The main issue with your current code is that the ArrayList
(pets
) is local to the PetList
constructor, which means that you can't access outside the constructor of the class PetList
.
So, first, make ArrayList
as an instance variable to the PetList
class so that it can be accessible through an object even outside the constructor.
Then, you can provide an eatAll()
method which iterates the ArrayList<Pet>
and call the eat()
method on all pet
objects.
You can refer the below 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 suggest you follow the Java naming standards (Eat()
should be eat()
i.e., method names should start with lowercase) and consider renaming PetList
class to PetsTesting
(or something else) so that it will be more intuitive for the developers.
Last, but important point is that don't assign the objects directly to the concrete class types like ArrayList<Pet> pets = new ArrayList<>();
or Puppies spot = new Puppies();
.
The best practice is that you need to assign the objects to the interface types List<Pet> pets = new ArrayList<Pet>();
or Pet spot = new Puppies();
(which is called code for the interface types)
public static void main(String[] args){
pets.foreach(pet::eat);
}
Should make them all eat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With