Java Reference
In-Depth Information
For example, the following statement avoids the ClassCastException from the previous
example by using the instanceof operator to determine the runtime type of the reference
mypet :
Pet mypet = new Dog(“Fido”, 2);
if(mypet instanceof Cat) {
((Cat) mypet).eat();
} else if(mypet instanceof Dog) {
((Dog) mypet).eat();
}
If mypet points to a Cat , we cast it to a Cat before invoking eat . If mypet points to a
Dog , we cast it to a Dog before invoking eat . The previous statements compile and run
successfully without a ClassCastException ever occurring.
The casting might seem odd, and you might be wondering why we don't just make the
mypet reference be of type Dog instead of Pet . The answer is that there are many real-world
situations in Java where a parent class reference is used to point to a child object, including
polymorphic parameters and heterogeneous collections, which I discuss next.
Polymorphic Parameters
A common use of polymorphism is with polymorphic parameters of a method. If a method
parameter is a class type, the argument passed in can be any child type of the class as well.
For example, the following Vet class contains a vaccinate method that takes in a Pet
reference:
public class Vet {
public void vaccinate(Pet pet) {
if(pet instanceof Dog) {
System.out.println(“Vaccinating a dog”);
Dog dog = (Dog) pet;
//use the dog reference
} else if(pet instanceof Cat) {
System.out.println(“Vaccinating a cat”);
Cat cat = (Cat) pet;
//use the cat reference
}
}
}
The argument passed into vaccinate can certainly be a Pet object, but you can also
pass in a Cat object, a Dog object, or any other object that is a child class of Pet . The
result is often a parent class reference pointing to a child class object, and we can use
the instanceof operator if we need to cast the reference to its appropriate child class type,
as demonstrated in the vaccinate method.
Search WWH ::




Custom Search