Showing posts with label casting. Show all posts
Showing posts with label casting. Show all posts

Friday, 22 April 2011

Casting Objects and instanceof

One of the difficulties of using a superclass array to hold many instances of subclass objects is that one can only access properties and methods that are in the superclass (ie. common to all). By casting an individual instance to its subclass form, one can refer to any property or method. But first take care to make sure the cast is valid by using the instanceof operator. Then perform the cast. As an example using the above Animal class:

if (ref[x] instanceof Dog) // ok right type of object
{
  Dog doggy = (Dog) ref[x]; // cast current instance to subclass
  doggy.someDogOnlyMethod();
}


Casts to subclass can be done implicitely but explicit casts are recommended. Casts to superclass must be done explicitly. Casts cannot be made between sibling classes.

Sunday, 26 September 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