by Dinesh Thakur

You can cast an object to another class type provided a class is a subclass of other i.e. casting takes place within an inheritance hierarchy, so that the source and destination are within the same hierarchy.

If s be a reference variable of type Shape and rect be a reference variable that holds object of type Rectangle. We can assign the Rectangle reference rect to the Shape reference variable s. This is accomplished using the following statements,

Shape s;

Rectangle rect = new Rectangle (10,20) ;

$ = rect;

In the last statement, the compiler implicitly casts a Rectangle type to a Shape type. This

is possible because as Rectangle is derived from Shape so each Rectangle object is an object of Shape class. Such type of casting in which an object implicitly casts to a superclass type is known as casting up through the class hierarchy.

Now let us consider the following statement in which we are attempting to implicit downcast a Shape type to a Rectangle.

rect = s ;

This is invalid statement and compiler will generate an error on compilation. This is because not all the instances of Shape are also instances of Rectangle. So if you want to make this statement work, you must cast it explicitly. For this, like with primitive types, enclose the class type that an object is being cast to (in our case Rectangle) in parentheses in front of the object reference s. So, the valid statement is

rect = (Rectangle)s;

Such type of casting in which an object explicitly casts to a subclass is known as casting down through the class hierarchy. For the casting to be successful, make sure that the object to be cast is an instance of subclass.

You will need to cast an object to a subclass type when you need to access a method that is unique to a subclass. For example, suppose the Rectangle class contains a method getLength () which returns the length of the rectangle. Since this method does not belong to Shape class and therefore cannot be invoked through a reference variable s of type Shape even though it references a Rectangle object. It must be invoked through a reference of type "Rectangle like recto So if you want to invoke a method getlength () , you must explicitly cast reference variable s to type

Rectangle using the following statement.

((Rectangle) s) .getLength (); .

In this statement, the object pointed to by s is first cast to type Rectangle and the result of cast is then used to invoke the method getLength () . If the method was not bf type Rectangle, the cast would, cause an exception to be thrown. For example

The statement,.

((Circle) s). getLength () ;

will throw an exception java.lang. ClassCastException as s 'currently holds the Rectangle object.

class Shape

{
     public void area()
     {
       System.out.println("Base class area mathod is called");
     }
}
class Rectangle extends Shape
{
      double length,breadth;
      Rectangle(double x,double y)
      {
        length = x ;
        breadth = y ;
      }
      public double getLength() { return length;}
      public double getBreadth()  { return breadth;}
      public void area()
      {
        System.out.println("Area of Rectangle is = "+ (length * breadth));
      }
}
   class Circle extends Shape
{
     private double radius;
     Circle(double r)
     {
        radius = r ;
     }
     public double getRadius() { return radius;}
     public void area()
     {
      System.out.println("Area of Circle is = " +(Math.PI*radius*radius));
     }
}
    class CastingObject
{
       public static void main(String[] args)
     {
        Shape s; //Shape class reference variable
        Rectangle r = new Rectangle(10,20);
        s = r; //Assign rectangle reference to shape reference
        System.out.println("Length = "+((Rectangle)s).getLength());
        System.out.println("Breadth = "+((Rectangle)s).getBreadth());
        s.area();
        Circle c = new Circle(5) ;
        s = c; //Assign circle reference to shape reference
        System.out.println("Radius = "+((Circle)s).getRadius());
        s.area();
     }
}

Casting Objects in Java Example