Prepare for the Object-Oriented Programming Test with flashcards and multiple choice questions. Each question comes with hints and explanations to enhance understanding. Master OOP concepts and succeed in your exam!

Multiple Choice

What is downcasting?

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.