Java Reference
In-Depth Information
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
The chances are that you will get a different set from this, and a different set again when you re-run the
example. The output from the example clearly shows that the methods are being selected at runtime,
depending on which object happens to get stored in the variable petChoice .
How It Works
The definition of the sound() method in the Animal class has no statements in the body, so it will do
nothing if it is executed. We will see a little later in this chapter how we can avoid including the empty
definition for the method, but still get polymorphic behavior in the derived classes.
We need the import statement because we use a Random class object in our example to produce
pseudo-random index values in the way we have seen before. The array theAnimals of type Animal
contains a Dog object, a Cat object and a Duck object. We select objects randomly from this array in
the for loop using the Random object, select , and store the selection in petChoice . We can then
call the toString() and sound() methods using the object reference stored. The effect is that the
appropriate method is selected automatically to suit the object stored, so our program operates
differently depending on what type of object is referenced by petChoice .
Of course, we call the toString() method implicitly in the argument to println() . The compiler
will insert a call to this method to produce a String representation of the petChoice object. The
particular toString() method will automatically be selected to correspond with the type of object
referenced by petChoice . This would still work even if we had not included the toString()
method in the base class. We will see a little later in this chapter there is a toString() method in
every class that you define, regardless of whether you define one or not.
Polymorphism is a fundamental part of object-oriented programming. We will be making extensive use
of polymorphism in many of the examples we will develop later in the topic, you will find that you will
use it often in your own applications and applets. But this is not all there is to polymorphism in Java,
and we will come back to it again later in this chapter.
Multiple Levels of Inheritance
As we indicated at the beginning of the chapter, there is nothing to prevent a derived class being used as
a base class. For example, we could derive a class Spaniel from the class Dog without any problem:
Search WWH ::




Custom Search