Friday, October 12, 2012

What is downcasting in java?


Suppose we have the following Java code in which a downcast is being performed:


class Parent{ /* ... */}

class ChildClass extends Parent { /* ... */ }

public class Tester {

     public static void main (String args[ ]) {
 
      Parent p = new Parent ( );
   
      /*this is a downcast since the Parent class
        object, "p" is being cast to a ChildClass type,
        and ChildClass derives from the Parent class */
   
      ChildClass c = (ChildClass) p;

     }
}



So, in downcasting, you are going down the inheritance diagram by taking an object of a base class (at the top), and then trying to convert into the type of one of the derived classes (going down)

ChildClass c = (ChildClass) p;

So, what happens when the code in our example above is run?

The code above will actually compile, but at runtime it will throw a Runtime Exception (a java.lang.ClassCastException).

If a Java expert would look at the code in our example up above, he or she would definitely know that the code would not work at run-time. So, why does it even compile? Well, remember that the compiler sees things differently from humans – and it thinks that the programmer knows what he is doing. But, in any case, the error is found at run time. By having the cast there (remember the cast is the “(ChildClass) p”), we are telling the compiler that we really do actually want to do this – it is not just a mistake in typing. So, the compiler trusts our judgement. But at runtime Java finds out that the object “p” is of the “ParentClass” type, and it will throw a Runtime Exception.

What if there was no type cast in the code above?
Suppose there is no type cast, and the critical line of code above is changed so that it looks like this:
ChildClass c =  p;

Then this code would give a compile time error instead of a runtime error – because there is no way that an object of the Parent class can ever be downcast to an object of it’s child class.

Is downcasting ever allowed in Java, and when would it be necessary?
Yes, downcasting is allowed in Java – if it wasn’t then the code up above would always return an error at compile time, not just at run-time.

Downcasting is very useful when you need to compare one object to another. An example would help clarify – take a look at the code below:




http://www.programmerinterview.com/index.php/java-questions/downcasting-in-java/





  • Downcasting


In object-oriented programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes.
In other words, when a variable of the base class (parent class) has a value of the derived class (child class), downcasting is possible.

For example in Java:

public class Parent{}
public class Child extends Parent(){}

public static void main(String args[]){
    Parent parent = new Child();              // Parent is parent class of Child, parent variable holding value of type Child
    Child child = (Child)parent;              // This is possible since parent object is currently holding value of Child class
}



Most often, you will encounter a need to do downcasting when passing a value in a parameter. So, in another example, let's say we have method objectToString that takes Object which we assume the parameter myObject is String type.

public String objectToString(Object myObject){
    return (String)myObject; //This will only work when the myObject currently holding value is string.
}

public static void main(String args[]){
    String result = objectToString("My String"); //This will work since we passed in String, so myObject has value of String.
    Object iFail = new Object();
    result = objectToString(iFail);              //This will fail since we passed in Object which does not have value of String.
}


The danger of downcasting in this approach is that it's not compile time check, but rather it is run time check



http://en.wikipedia.org/wiki/Downcasting