Casting

Type Wrapper Classes for Primitive Types

The syntax for casting gives the target type in parenthesis, followed by the variable's name or value to be cast:

int i = (int) f;

 


Casting Objects

Casting can be used to convert an object of one class type to another within an inheritance hierarchy.

To use explicit casting, enclose the target object type in parenthesis and place it before the object to be cast.

Oval myOval = (Oval) myCircle;

It is always possible to convert an instance of a subclass to an instance of a superclass.

When converting an instance of a superclass to a subclass, explicit casting must be used.

 

To invoke a method from a superclass, you must cast the subclass to the superclass, and enclose the casting expression in parenthesis before calling the method:

( (Circle) circle ).getRadius ( )

If the parenthesis are omitted, the expression is invalid:  (Circle) circle.getRadius ( )