Java Reference
In-Depth Information
}
Directory "Lay Eggs"
If you now try to use this with the code:
public class LayEggs {
public static void main(String[] args) {
Duck aDuck = new Duck("Donald", "Eider");
Animal aPet = aDuck;
// Cast the Duck to Animal
aPet.layEgg();
// This won't compile!
}
}
Directory "Lay Eggs"
you get a compiler message to the effect that layEgg() is not found in the class Animal .
Because you know this object is really a Duck , you can make it work by writing the call to layEgg() in
the preceding code 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.
WARNING In general, you should avoid explicitly casting objects as much as pos-
sible because 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 that I discussed in the previous section. A parameter of type Animal could have a
Duck , a Dog , or a Flea object passed as the argument. In some situations you may need to cast the object to
its actual class type, perhaps to call a class-specific method. If you try to make the cast and it turns out to
be illegal, an exception is thrown, and your program ends unless you have made provision for catching the
Search WWH ::




Custom Search