Page 557 - Introduction to Programming with Java: A Problem Solving Approach
P. 557
13.6 Assignments Between Classes in a Class Hierarchy 523
/**********************************************************
*
Pets2.java
Dean & Dean
This illustrates use of instanceof operator.
**********************************************************/
*
*
*
import java.util.Scanner;
public class Pets2
{
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"))
{
}
else
{
Apago PDF Enhancer
obj = new Cat();
obj = new Dog();
}
// end Pets2 class
}
// end main
}
if (obj instanceof Dog)
{
}
Sample session:
System.out.println("Wag tail");
Which type of pet do you prefer?
Enter d for dogs or c for cats: d
Wag tail
This condition evaluates to true
if the object referred to is an instance of the Dog class or a class descended from the Dog class.
Figure 13.7 Demonstration of instanceof operator
The “is a” mnemonic can help you remember the rule, but if you’re a Curious George,2 you probably want more. You probably want to understand the true rationale behind the rule. So here goes. It’s OK to as- sign a descendant-class object into an ancestor-class reference variable because all the compiler cares about is whether the assigned-in descendant-class object has all the members that any object of the reference vari- able’s class should have. And if you assign a descendant-class object to a ancestor-class reference variable, it does. Why? Because descendant-class objects always inherit all ancestor-class members!
2 Curious George is the main character in a series of books written by Margret and H. A. Rey. George is a curious monkey. Author John’s toddler, Caiden, is a Curious-George wannabe.
⎫ ⎪
⎪ ⎪ ⎬
⎪
⎪ ⎪ ⎭