Sunday, September 26, 2010

Run-Time Type Information and Casts

Rectangle r = new Rectangle (new Point (0,0), 5, 10);
Square s = new Square (new Point (0,0), 15);
Lets say that square extends rectangle.

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

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.
Enhanced by Zemanta

No comments:

Post a Comment