[FONT=Garamond]I'm 17 yrs old and I just started programming as a hobby. In need help in my Polymorphism program. how do to create an application that create an application that has an array of some size, say 5. The array should be defined of the superclass type.
Then create 5 objects where each class is represented at least once. Store the objects created into the array elements.
Finally, have the application go to each element of the array and call the display method. I should find that the display method automatically called is the one defined in the object stored in the element.
I already have a superclass which is animal and two subclasses dog and cat and a polymorphism application mainclass
Polymorphism Application MainClass
public class MainClass { public static void main(String [] args) { Animal a = new Animal(); a.displayName("Generic Animal"); Cat c = new Cat(); c.displayName("Fluffy"); Animal dog = new Dog(); dog.displayName("Scooby-Doo"); // Polymorphic method call -- Dog IS-A Animal Animal cat = new Cat(); cat.displayName("Mittens"); // Polymorphic method call -- Cat IS-A Animal } }
Superclass (Animal):
public class Animal { public void displayName(String name) { System.out.println("My name is " + name); } }
Subclass (Cat):
public class Cat extends Animal { public void displayName(String name) { System.out.println("My name is " + name + " and I like to drink milk."); } }
Subclass (Dog):
public class Dog extends Animal { public void displayName(String name) { System.out.println("My name is " + name + " and I like to eat Scooby Snacks!"); } }
Result:
My name is Generic Animal
My name is Fluffy and I like to drink milk.
My name is Scooby-Doo and I like to eat Scooby Snacks!
My name is Mittens and I like to drink milk.