Java Reference
In-Depth Information
Using Polymorphism
As we have seen, polymorphism relies on the fact that you can assign an object of a subclass type to a
variable that you have declared as being of a superclass type. Suppose you declare the variable:
Animal theAnimal; // Declare a variable of type Animal
You can quite happily make this refer to an object of any of the subclasses of the class Animal . For
example, you could use it to reference an object of type Dog :
theAnimal = new Dog("Rover");
As you might expect, you could also initialize the variable theAnimal when you declare it:
Animal theAnimal = new Dog("Rover");
This principle applies quite generally. You can use a variable of a base class type to store a reference to
an object of any class type that you have derived, directly or indirectly, from the base. We can see what
magic can be wrought with this in practice by extending our previous example. We can add a new
method to the class Dog that will display the sound a Dog makes. We can add a couple of new
subclasses that represent some other kinds of animals.
Try It Out - Enhancing the Dog Class
First of all we will enhance the class Dog by adding a method to display the sound that a dog makes:
public class Dog extends Animal {
// A barking method
public void sound() {
System.out.println("Woof Woof");
}
// Rest of the class as before...
}
We can also derive a class Cat from the class Animal :
public class Cat extends Animal {
public Cat(String aName) {
super("Cat"); // Call the base constructor
name = aName; // Supplied name
breed = "Unknown"; // Default breed value
}
public Cat(String aName, String aBreed) {
super("Cat"); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed
}
Search WWH ::




Custom Search