Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Run-Time Type Information and Casts

Consider the following declarations which make use of the Rectangle and Square classes defined in Programs gif and gif:

Rectangle r = new Rectangle (new Point (0,0), 5, 10);
Square s = new Square (new Point (0,0), 15);
Clearly, the assignment
r = s;
is valid because Square is derived from Rectangle. That is, since a Square is a Rectangle, we may assign s to r.

On the other hand, the assignment

s = r; // Wrong.
is not valid because a Rectangle instance is not necessarily a Square.

Consider now the following declarations:

Rectangle r = new Square (new Point (0,0), 20);
Square s;
The assignment s=r is still invalid because r is a Rectangle, and a Rectangle is not necessarily a Square, despite the fact that in this case it actually is!

In order to do the assignment, it is necessary to convert the type of r from a Rectangle to a Square. This is done in Java using a cast operator :

s = (Square) r;
The Java virtual machine checks at run-time that r actually does refer to a Square and if it does not, the operation throws a ClassCastException. (Exceptions are discussed in Section gif).

To determine the type of the object to which r refers, we must make use of run-time type information  . In Java every class supports the method getClass which returns an instance of java.lang.Class that represents the class of the object. Thus, we can determine the class of an object like this:

if (r.getClass() == Square.class)
    s = (Square) r;
This code does not throw an exception because the cast operation is only attempted when r actually is a Square.


next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.