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) { // This will only work when the myObject currently holding value is string. return (String)myObject; } public static void main(String[] args) { // This will work since we passed in String, so myObject has value of String. String result = objectToString("My String"); Object iFail = new Object(); // This will fail since we passed in Object which does not have value of String. result = objectToString(iFail); } 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 not 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. ==Considerations==