// Tyler Mi // Short program showing the benefits of polymorphism import java.util.*; public class Pets { public static void main(String[] args) { Dog d = new Dog("Cerberus", "Hellhound", 1000, 0); Cat c = new Cat("Garfield", "Orange Tabby", 10, 2, 100); List pets = new LinkedList<>(); pets.add(d); pets.add(c); for (Animal pet : pets) { System.out.println(pet.getName()); System.out.println(pet); pet.greet(); } Animal pet = new Dog("Cerberus", "Hellhound", 1000, 0); // The following line of code will have a compiler error // because Java checks if the declared type of pet, "Animal" // has the fetchBall() method, and it doesn't // pet.fetchBall() // We can fix convince the compiler that "pet" is a Dog for a // method call by casting it! ((Dog) pet).fetchBall(); // Note that we can also put a "Cat" object in the "pet" variable // because the type of the variable is Animal, so it can hold any Animal! pet = new Cat("Garfield", "Orange Tabby", 10, 2, 100); // We can still do the same cast to trick Java into thinking // the "pet" variable can call fetchBall, but we run into a // ClassCastException when we are running the code, because a // Cat is not a "suitable replacement" for a Dog, ie. it's not // a subclass ((Dog) pet).fetchBall(); } }