A wrong downcast throws ClassCastException
A Puppy passes a cast to Dog: a cast succeeds for the target type or any subclass of it.
Upcasting (child to parent type) is automatic and always safe. Downcasting (parent to child type) needs an explicit cast, is checked at run time, and throws ClassCastException if the object isn't really that type, so you test first with instanceof.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static double totalArea(Object[] items) that sums the area of every Circle and Square in the array (each with its own fields) and ignores anything else, using pattern matching.
Given Animal[] zoo = { new Dog(), new Cat(), new Dog() }, count how many are Dogs using instanceof.
Write a method that takes an Object and returns its length if it's a String, its size if it's a java.util.List, and -1 otherwise.
Explain it without notes
What's the difference between upcasting and downcasting? Which one can fail, and when?
What exactly does (Dog) a do at run time?
When does the compiler reject a cast outright?
What does pattern matching for instanceof add over test-then-cast?
Expected output
Dog -> Dog: OK, it is a Dog
Puppy -> Dog: OK, it is a Puppy
Cat -> Dog: Failed: ClassCastException
String is not an Integer