Page 553 - Introduction to Programming with Java: A Problem Solving Approach
P. 553

                13.5 Polymorphism and Dynamic Binding 519 13.5 Polymorphism and Dynamic Binding
Polymorphism Overview
If you ask an object-oriented programming (OOP) aficionado to name the three most important characteris- tics of OOP, he or she will probably answer “encapsulation, inheritance, and polymorphism.” The previous chapter discussed encapsulation and inheritance. Now it’s time to discuss polymorphism. The word poly- morphism comes from the Greek for “having many forms.” In chemistry and mineralogy, polymorphism is when a substance can crystallize in two or more alternative forms. In zoology, polymorphism is when a species has two or more different forms, like the different castes of bees spawned by the same queen to per- form different functions in a beehive. In computer science, polymorphism is when different types of objects respond differently to the same method call.
Here’s how it works. You declare a general type of reference variable that is able to refer to objects of different types. What is the most general type of reference variable? It’s an Object reference variable, de- clared, for example, like this:
Object obj;
Once you have declared a reference variable of type Object, you can use it to refer to any type of ob- ject. For example, suppose you define a class named Dog, as in Figure 13.4, and another class named Cat, as in Figure 13.5. Each of the two derived classes contains a toString method that overrides the toString method in the Object class. Notice that the two toString methods shown override Object’s toString method in different ways. One returns what a dog says, “Woof! Woof!”, and the
 other returns what a cat says, “Meow! Meow!”
Apago PDF Enhancer
The different toString method definitions in the Dog and Cat classes enable the toString method to be polymorphic. If you call toString with a reference to a Dog object, it responds the way a dog would respond, but if you call toString with a reference to a Cat object, it responds the way a cat would respond. The driver in Figure 13.6 demonstrates this effect. Notice how the obj reference variable can contain a reference to either a Dog object or a Cat object, and that object determines which toString method is called.
 /***************************************
*
Dog.java
Dean & Dean
This class implements a dog.
***************************************/
*
*
*
public class Dog
{
}
// end Dog class
public String toString()
{
}
return "Woof! Woof!";
Figure 13.4
Dog class for Pets program driven by code in Figure 13.6







































































   551   552   553   554   555