Java Reference
In-Depth Information
// Rest of the class as before...
// Dummy method to be implemented in the derived classes
public void sound(){}
}
We need a program that will use these classes. To give the classes a workout, we can create an array of
type Animal and populate its elements with different subclass objects. We can then select an object
random from the array, so that there is no possibility that the type of the object selected is known ahead
of time. Here's the code to do that:
import java.util.Random;
public class TryPolymorphism {
public static void main(String[] args) {
// Create an array of three different animals
Animal[] theAnimals = {
new Dog("Rover", "Poodle"),
new Cat("Max", "Abyssinian"),
new Duck("Daffy","Aylesbury")
};
Animal petChoice; // Choice of pet
Random select = new Random(); // Random number generator
// Make five random choices of pet
for(int i = 0; i < 5; i++) {
// Choose a random animal as a pet
petChoice = theAnimals[select.nextInt(theAnimals.length)];
System.out.println("\nYour choice:\n" + petChoice);
petChoice.sound(); // Get the pet's reaction
}
}
}
When I ran this I got the output:
Your choice:
This is a Duck
It's Daffy the Aylesbury
Quack quackquack
Your choice:
This is a Cat
It's Max the Abyssinian
Miiaooww
Your choice:
This is a Duck
It's Daffy the Aylesbury
Quack quackquack
Search WWH ::




Custom Search