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

                Figure 13.6 Driver for Pets program that includes classes in Figures 13.4 and 13.5
Compilation Details
In the a Pets program, we illustrated polymorphic behavior by calling Dog and Cat versions of the toString method. Could we have done the same thing with Dog and Cat versions of a display method? In other words, if Dog implemented a display method that prints “I’m a dog,” would the following code work?
Object obj = new Dog();
obj.display());
13.5 Polymorphism and Dynamic Binding 521
 /**********************************************************
*
Pets.java
Dean & Dean
This illustrates simple polymorphism.
**********************************************************/
*
*
*
import java.util.Scanner;
public class Pets
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
Object obj;
System.out.print("Which type of pet do you prefer?\n" +
"Enter d for dogs or c for cats: ");
if (stdIn.next().equals("d"))
  {
  }
obj = new Dog();
  }
// end Pets class
}
// end main
else
{
Apago PDF En
obj = new Cat();
}
 System.out.println(obj.toString()); ⎫ ⎬
System.out.println(obj); ⎭
Sample session:
 Which type of pet do you prefer?
Enter d for dogs or c for cats: d
Woof! Woof!
Woof! Woof!
The obj reference variable can contain a reference to either a Dog object or a Cat object.
hancer
That object determines which version of
the toString method is called here.
 These two statements are equivalent.


















































   553   554   555   556   557