Java Reference
In-Depth Information
class Object
is derived from
class Animal
is derived from
is derived from
is derived from
class Dog
class Cat
class Duck
is derived from
class Spaniel
You can cast an object of a class upwards through its direct and indirect superclasses. For example, you could
cast 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 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
and it 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 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 cast explicitly since the compiler is not prepared to insert it, and 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 above to type Dog or type Spaniel , since the object was
originally a Spaniel , but you could not cast it to Cat or Duck , since an object of type Spaniel does
not have Cat or Duck as a superclass. To cast theAnimal to type Dog , you would write:
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 .
Search WWH ::




Custom Search