I need assistance with polymorphis and interface in my project

Let’s walk through the instructions.

  1. Add at least one of each of your new animal types to the zoo in ZooTest.java

This would require implementing your interface in a subclass of Animal and adding an instance of it to the zoo list. e.g.

List<? extends Animal> zoo = new ArrayList<>();
zoo.add(new Fox());
zoo.add(new Dog());
zoo.add(new Bear());
// plus more?
  1. Create an array or ArrayList of Pets

Simple enough. Create a list with Pet as the type. A list makes more sense for this situation.

List<Pet> pets = new ArrayList<>();
  1. Loop through the zoo. If an animal is also a pet, add it to the pet array

In order to determine if an object is of a certain type, we can use the instanceof keyword. After that check, we can safely cast to the desired type.

if (animal instanceof Pet)
    pets.add((Peg) animal);
  1. Iterate through the pet array (which should only have pets) and have each pet do something that

Seems fairly obvious. Iterate the pets list.

for (Pet pet : pets) {
    ...
}

Leave a Comment