Java Reference
In-Depth Information
Duck aDuck = new Duck("Donald", "Eider");
Animal aPet = aDuck; // Cast the Duck to Animal
aPet.layEgg(); // This won't compile!
}
}
you will get a compiler message to the effect that layEgg() is not found in the class Animal .
Since you know this object is really a Duck , you can make it work by writing the call to layEgg() in
the code above as:
((Duck)aPet).layEgg(); // This works fine
The object pointed to by aPet is first cast to type Duck . The result of the cast is then used to call the method
layEgg() . If the object were not of type Duck , the cast would cause an exception to be thrown.
In general, you should avoid explicitly casting objects as much as possible, since it
increases the potential for an invalid cast and can therefore make your programs
unreliable. Most of the time you should find that if you design your classes carefully,
you won't need explicit casts very often.
Identifying Objects
There are circumstances when you may not know exactly what sort of object you are dealing with. This
can arise if a derived class object is passed to a method as an argument for a parameter of a base class type,
for example, in the way we discussed in the previous section. In some situations you may need to cast it to
its actual class type, perhaps to call a class specific method. If you try to make an illegal cast, an exception
will be thrown, and your program will end, unless you have made provision for catching it. One way to
obviate this situation is to test that the object is the type you expect before you make the cast.
We saw earlier in this chapter how we could use the getClass() method to obtain the Class object
corresponding to the class type, and how we could compare it to a Class instance for the class we are
looking for. You can also do this using the operator instanceof . For example, suppose you have a
variable, pet , of type Animal , and you want to cast it to type Duck . You could code this as:
Duck aDuck; // Declare a duck
if(pet instanceof Duck) {
aDuck = (Duck)pet; // It is a duck so the cast is OK
aDuck.layEgg(); // and we can have an egg for tea
}
If pet does not refer to a Duck object, an attempt to cast the object referenced by pet to Duck would cause
an exception to be thrown. This code fragment will only execute the cast and lay an egg if pet does point to
a Duck object. The code fragment above could have been written much more concisely as:
Search WWH ::




Custom Search