Casting |
| INTERMEDIATE |
Casting is changing the type of a variable or expression. The syntax for doing so is
(new_type)variable
or
(new_type)(expression)
Parentheses are necessary for most expressions because the cast operation has a very high precedence.
Casting primitive types
Any numeric primitive
type (char, short, int, long, float, double)
can be cast to any other numeric primitive type. When there is no danger
of loss of information, the cast can be implicit; otherwise it must be explicit.
For example, an int value can be assigned to a double variable:
double x = 5;
but an explicit cast must be used to assign a double value to an int variable
(which discards the fractional part):
int y = 5.85; // y gets the value 5
The allowable implicit casts are: byte or char → short → int → long → float → double.
Casting object types
Objects of one type can be cast to a different
type if and only if one of the types is an ancestor of the other. Upcasting is casting to an ancestor type; downcasting is casting to a descendant type.
For example, if Poodle extends Dog and Dog extends Animal, then the following
casts (among others) are possible:
Poodle fifi = new Poodle();
Dog myDog = fifi; // implicit upcasting
myDog = (Dog)fifi; // explicit upcasting
Poodle yourPoodle = (Poodle)yourDog; // downcasting (must be explicit)
When downcasting an object, Java inserts an implicit check that the object
really is the more specific type, and throws a ClassCastException if it is
not. In the last example above, an error results if yourDog is not actually
a Poodle.
The usual reason for upcasting is to put an object into a collection of more general objects; for example, to put a poodle into an array of dogs. The usual reason for downcasting is to be able to use the added features of the more specific object when retrieving an object from a collection of more general objects.