From Wikipedia, the free encyclopedia
Jump to: navigation, search


In many programming languages, it is possible to check through type introspection to determine whether the type of the referenced object is indeed the one being cast to or a derived type of it, and thus issue an error if it is not the case.



In Java:

public class Parent{}
public class Child extends Parent{}
public static void main(String args[]) {
    Parent parent = new Child();  // a variable holding a value of type Child
    Child child = (Child)parent;  // OK since parent variable is currently holding Child instance


Downcasting is useful when the type of the value referenced by the Parent variable is known and often is used when passing a value as a parameter. In the below example, the method objectToString takes an Object parameter which is assumed to be of type String.

public static 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.

In this approach, downcasting prevents the compiler from detecting a possible error and instead causes a run-time error. Downcasting myObject to String ('(String)myObject') was possible at compile time because there are times that myObject is String type, so only at run time can we figure out whether the parameter passed in is logical. While we could also convert myObject to a compile-time String using the universal java.lang.Object.toString(), this would risk calling the default implementation of toString() where it was unhelpful or insecure, and exception handling could not prevent this.

In C++, run-time type checking is implemented through dynamic_cast. Compile-time downcasting is implemented by static_cast, but this operation performs no type check. If it is used improperly, it could produce undefined behavior.


Many people advocate avoiding downcasting, since according to the LSP, an OOP design that requires it is flawed. Some languages, such as OCaml, disallow downcasting altogether.[1]

A popular example of a badly considered design is containers of top types, like the Java containers before Java generics were introduced, which requires downcasting of the contained objects so that they can be used again.

See also[edit]

External links[edit]