Saturday, April 23, 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.

No comments:

Post a Comment

Chitika