Skip to content

Chapter 12 of 37

Polymorphism

Understand overload selection, overriding, dynamic dispatch, upcasting, and type patterns.

36 minutes 10 quick checksBy Subha Prasad
Lesson 12 of 37Course navigation

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.

Which statement best describes compile-time polymorphism?
Which Java term matches this description: Overload selection based on declared argument types.
Which statement best describes runtime polymorphism?
Which Java term matches this description: Overridden instance-method selection from the actual object type.
Which statement best describes upcasting?
Which Java term matches this description: Treating a subtype reference as one of its supertypes.
Which statement best describes dynamic dispatch?
Which Java term matches this description: Runtime selection of the most specific overriding method.
Which statement best describes pattern matching instanceof?
Which Java term matches this description: A type test that also introduces a safely cast variable.

0 of 10 checks passed

Your progress is saved on this device.

Polymorphism | Java Lesson | Subha Prasad