Java Reference
In-Depth Information
You can cast a reference to an object of a given class type upwards through its direct and indirect su-
perclasses. 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
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. Because inform-
ation about the original type of an object is retained, you can cast down a hierarchy as well. However, you
must always write the cast explicitly because the compiler is not prepared to insert it. For the cast to work,
the object must be a legitimate instance of the class you are casting to — that is, the class you are casting to
must be the original class of the object, or must be a superclass of the object. For example, you could cast
a reference stored in the variable
theAnimal
shown in the preceding example to type
Dog
or type
Spaniel
because the object was originally a
Spaniel
, but you could not cast it to
Cat
or
Duck
because an object of
type
Spaniel
does not have
Cat
or
Duck
as a superclass. To cast
theAnimal
to type
Dog
, you would write
the following:
Dog aDog = (Dog)theAnimal; // Cast from Animal to Dog
Now the variable
aDog
refers to an object of type
Spaniel
that also happens to be a
Dog
. Remember,
you can only use the variable
aDog
to call the polymorphic methods from the class
Spaniel
that override
methods that exist in
Dog
. You can't call methods that are not defined in the
Dog
class. If you want to call a
method that is in the class
Spaniel
and not in the class
Dog
, you must first cast
aDog
to type
Spaniel
.