Java Reference
In-Depth Information
Try It Out - A
Spaniel
Class
Start the
Spaniel
class off with this minimal code:
class Spaniel extends Dog {
public Spaniel(String aName) {
super(aName, "Spaniel");
}
}
To try this out you can add a
Spaniel
object to the array
theAnimals
in the previous example, by
changing the statement to:
Animal[] theAnimals = {
new Dog("Rover", "Poodle"),
new Cat("Max", "Abyssinian"),
new Duck("Daffy","Aylesbury"),
new Spaniel("Fido")
};
Don't forget to add in the comma after the
Duck
. Try running the example again.
How It Works
The class
Spaniel
will inherit 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 once more, 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
methods
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 class
Animal
, we introduced a version of the method
sound()
that did nothing because we
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.