Java Reference
In-Depth Information
belongs. This implies that a variable of type Dog can only be used to access data members of the Dog class.
Even when it references an object of a derived type, Spaniel, for example, you can only use it to access
data members of the Dog part of a Spaniel object.
Using Polymorphism
As you have seen, polymorphism relies on the fact that you can assign an object of a subclass type to a vari-
able that you have declared as being of a superclass type. Suppose you declare the variable:
Animal theAnimal = null; // Declare a variable of type Animal
You can quite happily make theAnimal 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 to reference an object 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. You can see what
magic can be wrought with this in practice by extending the previous example. You can add a new method
to the class Dog that displays the sound a Dog makes. You can add a couple of new subclasses that represent
some other kinds of animals.
TRY IT OUT: Listening to the Animals
This example provides animals with a voice via a sound() method. I put the source files in a folder
with the name AnimalVoices . You need to make one change to the class Animal . To select the method
sound() dynamically for derived class objects, it needs to be a member of the base class. Add a content-
free version of a method sound() to the Animal class:
class Animal {
// Rest of the class as before...
// Dummy method to be implemented in the derived classes
public void sound(){}
}
Directory "AnimalVoices"
Search WWH ::




Custom Search