Tuesday, May 4, 2010

Casting

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.

A widening conversion is a conversion from a smaller numeric type to a larger numeric type. An
example of a widening conversion is when a byte value is promoted to an int value. A narrowing
conversion is a conversion from a larger numeric type to a smaller numeric type. A conversion from a
long value to a short value would be an example of a narrowing conversion. Narrowing conversions
require the use of the cast operator.

double d = 123.456;
byte b;
b = (byte) d;

Rules for casting
When casting is used with object references, the following rules apply:
1. A reference to any object can be cast into a reference to an object of class Object.
String s = "abcd';
Object o = s;

2. A reference to an object can be cast into a reference to an object of class C', if the actual class of the object is a subclass of C'.
Subclass s = ...  ;
Base b = s;

3. A reference to an object can be cast into a reference to an object of interface I, if the actual class of the object implements I, if the object is of interface type I' and I' is a subinterface of I, or if the object is an array type and I is the Cloneable interface.
class X implements I{}
X x = ... ;
I i = x;
For example, a Vector object can be cast to a List object, and a List object can be cast to a Collection object. Because the array type implements the Cloneable interface, any array can be cast into a Cloneable object.

4. A reference to an object can be cast a reference to an object of an array type (with element reference type T), if the object is of an array type (with element reference type T') such that T' can be cast into T.

Casting to array types is more complicated. In order to cast to 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.
As an example of object type casting, consider the following program. Without the (String) cast operator, the result returned by v.elementAt(0) is an object of the Object class. The compiler recognizes this inconsistency and generates an error message. When the (String) cast operator is used, the compiler recognizes that you are casting the reference to an Object object into a String object and proceeds with the compilation.

String s1 = "abc";
String s2 = "def";
Vector v = new Vector();
v.add(s1);
s2 = (String) v.elementAt(0);
System.out.println(s2);

No comments:

Post a Comment

Chitika