出典(authority):フリー百科事典『ウィキペディア(Wikipedia)』「2012/11/20 19:30:49」(JST)
This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. (August 2008) |
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 many programming languages, it is possible to check through RTTI 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 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 }
As you see, the downcasting is useful if we know the type of the value referenced by the Parent variable.
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. Downcasting myObject to String ('(String)myObject') was possible in compile time because there are times that myObject is String type, so only in run time we can figure out whether the parameter passed in is logical.
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.
Useful source introducing concept of downcasting: "Upcasting, downcasting" by Sinipull
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.
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.
.