What is the difference between upcasting and downcasting, and how do you do each one safely?
Upcasting is when you treat a child object as its parent type. Downcasting is when you go back the other way and treat a parent object as its child type.
public class Main {
public static void main(String[] args) {
Shape s = new Circle(2.0);
System.out.println(s.getClass().getSimpleName()); // Circle
}
}
And here is the safe way to do the downcast.
public class Main {
public static void main(String[] args) {
Shape s = new Circle(2.0);
if (s instanceof Circle) {
Circle c = (Circle) s;
System.out.println(c.radius());
}
}
}
So what is the difference between them? Here it is.
the thing the direction is it safe
---------------- ------------------------ ------------------
upcasting child to parent yes, always safe
downcasting parent to child only if it is right
And the reason upcasting is always safe is the substitutability promise. A Circle really is a Shape, so anywhere a Shape is wanted a Circle can go. The object itself does not change at all, only the way your code refers to it.
And the downcast is the one that can go wrong, because the parent object might not be a child at all. If you hold a Shape that is really a Square and you cast it to a Circle, then the cast fails at runtime and the program stops with a ClassCastException.
And so how do you do each one safely? The upcast is implicit, you do not need to write anything. The downcast has two safe forms. The first one is the pattern matching that came in with Java 16, where the compiler does the check and the cast at the same time.
if (s instanceof Circle c) {
System.out.println(c.radius());
}
And the second one is the old form, where you check and then cast on the next line. And the reason the check has to be a separate step in the old form is that the cast is done at runtime and the check is done by you, so you have to write the check before the cast or the cast can fail.
the form the safe version
-------------------------------- ----------------------------------
(Circle) s no, it can throw
if (s instanceof Circle) yes, but you cast twice
{ Circle c = (Circle) s; }
if (s instanceof Circle c) yes, and you cast once
So the rule to remember is this. The upcast is free and the downcast has to be checked first.
The last question in this topic is about why Java treats them differently.