What is downcasting?

Get ready for your Object‑Oriented Programming Test. Use flashcards and multiple-choice questions. Each question includes hints and explanations. Prepare for your exam today!

Multiple Choice

What is downcasting?

Explanation:
Downcasting is explicitly converting a reference from a superclass type to a subclass type. You must write the cast yourself, and it can fail at runtime if the actual object isn’t an instance of that subclass. For example, in Java you might have a base reference holding a derived object: Animal a = new Dog(); Then downcast: Dog d = (Dog) a;. This is valid only if a really refers to a Dog; if a referred to a Cat instead, the cast would throw a runtime error. This is why downcasting is distinct: it relies on an explicit cast and carries the risk of a runtime failure when the actual object isn’t the targeted subclass. It’s opposite to upcasting, where you convert a subclass reference to a superclass type and it’s safe and often implicit. The other options describe boxing primitives, not converting between supertype and subtype.

Downcasting is explicitly converting a reference from a superclass type to a subclass type. You must write the cast yourself, and it can fail at runtime if the actual object isn’t an instance of that subclass.

For example, in Java you might have a base reference holding a derived object: Animal a = new Dog(); Then downcast: Dog d = (Dog) a;. This is valid only if a really refers to a Dog; if a referred to a Cat instead, the cast would throw a runtime error.

This is why downcasting is distinct: it relies on an explicit cast and carries the risk of a runtime failure when the actual object isn’t the targeted subclass. It’s opposite to upcasting, where you convert a subclass reference to a superclass type and it’s safe and often implicit. The other options describe boxing primitives, not converting between supertype and subtype.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy