Recall & Review
beginner
What is upcasting in Java?
Upcasting is when you convert a subclass object to a superclass type. It is safe and done automatically by Java.Click to reveal answer
beginner
What is downcasting in Java?
Downcasting is when you convert a superclass reference back to a subclass type. It requires explicit casting and can cause errors if done incorrectly.Click to reveal answer
intermediate
Why is upcasting considered safe?
Because every subclass object is also an instance of its superclass, so no data or behavior is lost when upcasting.Click to reveal answer
intermediate
What happens if downcasting is done incorrectly?
Java throws a <code>ClassCastException</code> at runtime if the object is not actually an instance of the subclass you are casting to.Click to reveal answer
beginner
Show a simple Java example of upcasting and downcasting.
class Animal {}<br>class Dog extends Animal {}<br><br>Animal a = new Dog(); // upcasting<br>Dog d = (Dog) a; // downcastingClick to reveal answer
Which of the following is true about upcasting?
✗ Incorrect
Upcasting is automatic and safe because a subclass object is always an instance of its superclass.
What must you do to perform downcasting in Java?
✗ Incorrect
Downcasting requires explicit casting syntax like (Subclass) object.
What exception can occur if downcasting is done incorrectly?
✗ Incorrect
ClassCastException is thrown when you try to cast an object to a type it is not an instance of.
Given:
Animal a = new Dog(); What is this an example of?✗ Incorrect
Assigning a subclass object to a superclass reference is upcasting.
Which keyword helps check type before downcasting?
✗ Incorrect
The instanceof keyword checks if an object is an instance of a class before downcasting.
Explain the difference between upcasting and downcasting in Java.
Think about which direction the object reference is converted.
You got /4 concepts.
Describe a real-life example that helps you understand upcasting and downcasting.
Consider a general category and a specific item within it.
You got /3 concepts.