Page 554 - Introduction to Programming with Java: A Problem Solving Approach
P. 554
520 Chapter 13 Inheritance and Polymorphism
/**************************************
*
Cat.java
Dean & Dean
This class implements a cat.
**************************************/
*
*
*
public class Cat
{
}
public String toString()
{
}
return "Meow! Meow!";
// end Cat class
Figure 13.5 Cat class for Pets program driven by code in Figure 13.6
Why does the program print “Woof! Woof!” twice? There are two print statements. The first one ex-
plicitly calls a toString method. The second one uses an implicit call to a toString method—when a
reference variable appears alone in a String context, the compiler automatically appends .toString()
to the bare reference variable. So the last two statements in the Pets class are equivalent. Apago PDF Enhancer
Dynamic Binding
The terms polymorphism and dynamic binding are intimately related, but they’re not the same. It’s helpful to know the difference. Polymorphism is a form of behavior. Dynamic binding is the mechanism for that behavior—how it’s implemented. Specifically, polymorphism is when different types of objects respond differently to the exact same method call. Dynamic binding is what the JVM does in order to match up a polymorphic method call with a particular method.
Just before the JVM executes a method call, it determines the type of the method call’s actual calling object. If the actual calling object is from class X, the JVM binds class X’s method to the method call. If the actual calling object is from class Y, the JVM binds class Y’s method to the method call. After the JVM binds the appropriate method to the method call, the JVM executes the bound method. For example, note the obj.toString method call in the following statement near the bottom of Figure 13.6:
System.out.println(obj.toString());
Depending on which type of object is referred to by obj, the JVM binds either Dog’s toString method or Cat’s toString method to the obj.toString method call. After binding takes place, the JVM ex- ecutes the bound method and prints either “Woof! Woof!” or “Meow! Meow!”
Dynamic binding is referred to as “dynamic” because the JVM performs the binding operation while the program is running. The binding takes place at the latest possible moment, right before the method is executed. That’s why dynamic binding is often referred to as late binding. By the way, some programming languages bind method calls at compile time rather than at runtime. That type of binding is called static binding. Java’s designers decided to go with dynamic binding rather than static binding because dynamic binding facilitates polymorphism.