Java Reference
In-Depth Information
class Spaniel extends Dog {
public Spaniel(String aName) {
super(aName, "Spaniel");
}
}
Directory "AnimalVoices"
To try this out you can add a
Spaniel
object to the array
theAnimals
in the previous example, by chan-
ging the statement to the following:
Animal[] theAnimals = {
new Dog("Rover", "Poodle"),
new Cat("Max", "Abyssinian"),
new Duck("Daffy","Aylesbury"),
new Spaniel("Fido")
};
Directory "AnimalVoices"
Don't forget to add in the comma after the
Duck
object. Try running the example again a few times.
How It Works
The class
Spaniel
inherits members from the class
Dog
, including the members of
Dog
that are inherited
from the class
Animal
. The class
Dog
is a direct superclass, and the class
Animal
is an indirect superclass
of the class
Spaniel
. The only additional member of
Spaniel
is the constructor. This calls the
Dog
class
constructor using the keyword
super
and passes the value of
aName
and the
String
object
"Spaniel"
to
it.
If you run the
TryPolymorphism
class a few times, you should get a choice of the
Spaniel
object from
time to time. Thus, the class
Spaniel
is also participating in the polymorphic selection of the meth-
ods
toString()
and
sound()
, which in this case are inherited from the parent class,
Dog
. The inherited
toString()
method works perfectly well with the
Spaniel
object, but if you wanted to provide a unique
version, you could add it to the
Spaniel
class definition. This would then be automatically selected for
a
Spaniel
object rather than the method inherited from the
Dog
class.
ABSTRACT CLASSES
In the
Animal
class, you introduced a version of the
sound()
method that did nothing because you wanted
to call the
sound()
method in the subclass objects dynamically. The method
sound()
has no meaning in
the context of the generic class
Animal
, so implementing it does not make much sense. This situation often
arises in object-oriented programming. You will often find yourself creating a superclass from which you
will derive a number of subclasses, just to take advantage of polymorphism.