6.9. Casting Objects

You can cast an object to another class type, but only if the current object type and the new class type are in the same hierarchy of derived classes, and one is a superclass of the other. For example, earlier in this chapter you defined the classes Animal, Dog, Spaniel, Cat, and Duck, and these classes are related in the hierarchy shown in Figure 6-5.

You can cast a reference to an object of a class upwards through its direct and indirect superclasses. For example, you could cast a reference to an object of type Spaniel directly to type Dog, type Animal, or type Object. You could write:

Spaniel aPet = new Spaniel("Fang");
Animal theAnimal = (Animal)aPet;       // Cast the Spaniel to Animal

When you are assigning an object reference to a variable of a superclass type, you do not have to include the cast. You could write the assignment as:

Animal theAnimal = aPet;               // Cast the Spaniel to Animal
Figure 6.5. Figure 6-5

This would work just as well. The compiler is always prepared to insert a cast to a superclass type when necessary.

When you cast an object reference to a superclass type, Java retains full knowledge of the actual class to which the object belongs. If this were not the case, polymorphism would not be possible. Since information about the original type of an object is retained, you can cast down a hierarchy as well. However, you must always write the ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.