Java Reference
In-Depth Information
FIGURE 6-4
A few requirements must be fulfilled to get polymorphic behavior, so let's step through them.
First of all, polymorphism works with derived class objects. It also depends on a new capability that is
possible within a class hierarchy that you haven't met before. Up to now you have always been using a vari-
able of a given type to reference objects of the same type. Derived classes introduce some new flexibility in
this. Of course, you can store a reference to a derived class object in a variable of the derived class type, but
you can also store it in a variable of any direct or indirect base class type. More than that, a reference to a
derived class object must be stored in a variable of a direct or indirect class type for polymorphism to work.
For example, Figure 6-4 illustrates how a variable of type Dog can be used to store a reference to an object
of any type derived from Dog . If the Dog class were derived from the Animal class here, a variable of type
Animal could also be used to reference Spaniel , Chihuahua , or Collie objects.
Polymorphism means that the actual type of the object involved in a method call determines which meth-
od is called, rather than the type of the variable being used to store the reference to the object. In Figure 6-4 ,
if aDog contains a reference to a Spaniel object, the bark() method for that object is called. If it contains a
reference to a Collie object, the bark() method in the Collie class is called. To get polymorphic operation
when calling a method, the method must be declared as a member of the base class — the class type of the
variable you are using — as well as being declared as a member of the class type of the object involved.
So in the example, the Dog class must contain a bark() method, as must each of the derived classes. You
cannot call a method for a derived class object using a variable of a base class type if the method is not a
member of the base class. Any definition of the method in a derived class must have the same signature as
in the base class and must have an access specifier that is no more restrictive.
Methods that have the same signature have the same name, and have parameter lists with the same num-
ber of parameters and corresponding parameters are of the same type. You have a bit more flexibility with
 
Search WWH ::




Custom Search