Wednesday, March 28, 2012

Object Reference Type Casting in Java

In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java.
How to Typecast Objects with a dynamically loaded Class ? – The casting of object references depends on the relationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object, because the Object class is a superclass of every Java class.
There can be 2 casting java scenarios
· Upcasting
· Downcasting


When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses, it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it is an upcast. We need not use a cast operator in this case.
The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship) At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is being cast to.
Below is an example showing when a ClassCastException can occur during object casting

//X is a supper class of Y and Z which are sibblings.
public class RunTimeCastDemo {

 public static void main(String args[]) {
  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 (siblings)
  //  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 of X)
  X x2 = z; // compiles ok (z is subclass of X)
  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 (siblings)
  //  Z z3 = (Z) y;     inconvertible types (siblings)
  Object o = z;
  Object o1 = (Y) o; // compiles ok but produces runtime error
 }
}

No comments:

Post a Comment