0
0
Javaprogramming~5 mins

Upcasting and downcasting in Java - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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; // downcasting
Click to reveal answer
Which of the following is true about upcasting?
AIt is automatic and safe.
BIt requires explicit casting.
CIt can cause ClassCastException.
DIt converts superclass to subclass.
What must you do to perform downcasting in Java?
AUse the instanceof keyword only.
BNothing, it is automatic.
CUse explicit casting syntax.
DDeclare a new superclass object.
What exception can occur if downcasting is done incorrectly?
AIllegalArgumentException
BArrayIndexOutOfBoundsException
CNullPointerException
DClassCastException
Given: Animal a = new Dog(); What is this an example of?
AUpcasting
BEncapsulation
CPolymorphism
DDowncasting
Which keyword helps check type before downcasting?
Acast
Binstanceof
Ctypeof
Dcheck
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.