0
0
Javaprogramming~10 mins

Upcasting and downcasting in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to upcast a Dog object to an Animal reference.

Java
Animal animal = new Dog(); // [1]
Drag options to blanks, or click blank then click option'
Aoverriding
Bdowncasting
Cupcasting
Doverloading
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Confusing upcasting with downcasting.
Trying to cast explicitly when not needed.
2fill in blank
medium

Complete the code to downcast an Animal reference back to a Dog object.

Java
Dog dog = (Dog) [1];
Drag options to blanks, or click blank then click option'
Aanimal
Bnew Animal()
Cnew Dog()
Danimal.toString()
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Trying to cast a new Animal object instead of the reference.
Missing the explicit cast.
3fill in blank
hard

Fix the error in the downcasting code to avoid ClassCastException.

Java
if ([1] instanceof Dog) {
    Dog dog = (Dog) animal;
}
Drag options to blanks, or click blank then click option'
Adog
Banimal
Cnew Animal()
Dnew Dog()
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Checking instanceof on the wrong variable.
Not using instanceof before downcasting.
4fill in blank
hard

Fill both blanks to create a list of Animals and add a Dog object using upcasting.

Java
List<[1]> animals = new ArrayList<>();
animals.add(new [2]());
Drag options to blanks, or click blank then click option'
AAnimal
BDog
CCat
DObject
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using Dog as the list type instead of Animal.
Adding an unrelated class object.
5fill in blank
hard

Fill all three blanks to safely downcast and call a Dog-specific method.

Java
if ([1] instanceof [2]) {
    [2] dog = ([2]) [3];
    dog.bark();
}
Drag options to blanks, or click blank then click option'
Aanimal
BDog
CCat
Dobject
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the wrong variable for instanceof or casting.
Casting to the wrong class.