Lesson content
Read, practise, then check your understanding
Compile-time polymorphism chooses an overload from declared argument types. Runtime polymorphism dispatches an overridden instance method from the receiver’s actual class. Fields and static methods are not dynamically dispatched.
Program to a supertype
static double totalArea(List<? extends Shape> shapes) {
double total = 0;
for (Shape shape : shapes) {
total += shape.area(); // dynamic dispatch
}
return total;
}
if (value instanceof Rectangle rectangle) {
System.out.println(rectangle.area());
}
Upcasting is safe and implicit. Downcasting requires a runtime check and can throw ClassCastException; pattern matching combines test and binding. The Liskov substitution principle requires subtype objects to honor expectations of the supertype. Prefer virtual behavior over type-switching when the type family is open, and sealed hierarchies with exhaustive pattern selection when it is deliberately closed.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.