Mastering upcasting and downcasting
Earlier, we touched upon why we get ClassCastException
errors. The rule is that a reference can refer to objects of its own type or objects of subclasses. In effect, a reference can point across and down the inheritance hierarchy, but never up. If a reference does point up the hierarchy, you will get a ClassCastException
error. Recall that the reason this occurs is that the subclass reference could have extra methods that any superclass object would have no code for. Whether that is the case or not is immaterial, could have is enough.
Keep in mind that assignment works from right to left; so, when reading code involving upcasting/downcasting, the direction in the hierarchy is from right to left as well. In addition, remember that the compiler is always looking at the reference type.
Now, let’s discuss, with the aid of code examples, both upcasting and downcasting. Let’s start with upcasting.
Upcasting
With upcasting, you...