Java Reference
In-Depth Information
This is a Cat
It's Max the Abyssinian
Miiaooww
The chances are good that you will get a different set than this, and a different set again when you rerun
the example. The output from the example clearly shows that the methods are being selected at run time,
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 does noth-
ing if it is executed. You see a little later in this chapter how you can avoid including the empty definition
for the method but still get polymorphic behavior in the derived classes.
You need the
import
statement because you use a
Random
class object in the example to produce pseudo-
random index values in the way you have seen before. The array
theAnimals
of type
Animal
contains a
Dog
object, a
Cat
object, and a
Duck
object. You select objects randomly from this array in the
for
loop
using the
Random
object
select
, and store the selection in
petChoice
. You 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 the program operates differently depending on what type of
object is referenced by
petChoice
.
Of course, you call the
toString()
method implicitly in the argument to
println()
. The compiler in-
serts a call to this method to produce a
String
representation of the object referenced by
petChoice
.
The particular
toString()
method is automatically selected to correspond with the type of object refer-
enced by
petChoice
. This would still work even if you had not included the
toString()
method in the
base class. You see a little later in this chapter that 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. You make extensive use of poly-
morphism in many of the examples you develop later in the topic, and you will find that you use it often
in your own applications and applets. But this is not all there is to polymorphism in Java, and I will come
back to it again later in this chapter.
MULTIPLE LEVELS OF INHERITANCE
As I indicated at the beginning of the chapter, there is nothing to prevent a derived class from being used as
a base class. For example, you could derive a class
Spaniel
from the class
Dog
without any problem:
TRY IT OUT: A Spaniel Class
Start the
Spaniel
class off with this minimal code: