Home   Cover Cover Cover Cover
 

Type cast

Question: Does a type cast convert the static or the dynamic type of a variable? Give reasons for your answer.

Answer: A type casts converts the static type and not the dynamic type of a variable or expression. The dynamic type is the type that an object has at run time. This type cannot change. Otherwise the identity of the object would get lost. In contrast, the static type is the type under which the compiler sees an object and which it uses for type checking. The static type is either identical to the dynamic type of an object or it is a base type of it (i.e. the compiler may see less fields and methods than an object really has). A type cast is used to bring the static type of an object closer to its dynamic type or to make it identical to the dynamic type.