|
|
Operators and Assignments - Cast Operator
- the cast operator (type) is used to convert numeric values from one numeric type to another or to change an object reference to a compatible type
- used to enable conversions that would normally be disallowed by the compiler
byte a = 1;
byte b = 2;
byte c = a + b; // a and b are promoted to int
byte c = (byte)(a + b); // compiles ok
Casting with Object references (JLS §5.5, JJ pg 67)
- a reference of any object can be cast to a reference of type Object
- a reference to an object can be cast into a reference of type ClassName if the actual class of the object, when it was created, is a subclass of ClassName
- a reference to an object can be cast into a reference of type InterfaceName if the class of the object implements Interface, if the object is a subinterface of InterfaceName or if the object is an array type and InterfaceName is the Cloneable interface
If you cast up the class hierarchy you do not have to use the cast operator; if you are cast down the class hierarchy you must use the cast operator (BB pg 41)
However, the compiler uses the declared type to verify the correctness of each method call; which means you cannot invoke a subclass method from a superclass reference.
(See post by Michael Ernest at JavaRanch)
X x = new X();
Y y = new Y();
Z z = new Z();
X xy = new Y(); // compiles ok (up the hierarchy)
X xz = new Z(); // compiles ok (up the hierarchy)
Y yz = new Z(); // incompatible type
Y y1 = new X(); // X is not a Y
Z z1 = new X(); // X is not a Z
X x1 = y; // compiles ok (y is subclass)
X x2 = z; // compiles ok (z is subclass)
Y y1 = (Y) x; // compiles ok but produces runtime error
Z z1 = (Z) x; // compiles ok but produces runtime error
Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
Y y3 = (Y) z; // inconvertible types (casts sideways)
Z z3 = (Z) y; // inconvertible types (casts sideways)
Object o = z;
Object o1 = (Y)o; // compiles ok but produces runtime error
The casts work at compile time since the cast variable could conceivably be of a compatible type; however, at runtime the type of the variable is known and if it cannot guarantee to implement the contract of the cast type a
java.lang.CastClassException will be thrown.
Casting with arrays
- to cast an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference
double arr[] = {1.5, 2.256, 3.59};
int arr1[] = (int) arr; // compile-error
X[] arrX = { new X(), new X(), new X() };
Y[] arrY = { new Y(), new Y(), new Y() };
arrX = arrY; // compiles ok
Also see:
Example Code
Tips
- you cannot cast a primitive type to an object reference, or vice versa
- you cannot cast a boolean type to another primitive type
Traps
- result of an integer operation on byte or short types being assigned to a byte or short without an explicit cast
|