Java · Intermediate level

Intermediate level · Module 1: Inheritance, Interfaces and Polymorphism · Lesson 3 of 3

Polymorphism and Composition

Write code against interfaces so it works with any implementation, and prefer composition when inheritance does not fit.

In this lesson you will

  • Use polymorphism to process mixed objects through a shared type
  • Refactor an inheritance design into composition where appropriate

Key concepts

polymorphismprogram to an interfaceinstanceof and pattern matchingcomposition

The lesson

Polymorphism means one piece of code works with many types. A method processPayments(List<PaymentMethod> payments) calls pay() on each item, and Java runs the right version for each object at run time. Adding a new payment type needs a new class, not a change to processPayments.

If you find yourself writing long if (x instanceof A) … else if (x instanceof B) chains, the behaviour usually belongs in an overridden method instead. Java's pattern matching (if (p instanceof CashPayment c)) is useful, but it should not replace good design.

Composition means a class holds other objects instead of inheriting from them. A Car has an Engine rather than being an Engine. Composition is more flexible, because you can swap the parts, and it avoids fragile deep hierarchies.

Step by step

  1. Write processPayments that takes a List<PaymentMethod>.
  2. Add a BankTransferPayment and check that processPayments did not change.
  3. Find an instanceof chain in sample code and replace it with an overridden method.
  4. Redesign a Truck extends Engine example using composition.

Practice activity

Complete the shop payments activity: process a list of mixed payments, print a receipt for each and total the amount received per payment type.

Expected result: Adding a new payment class works without changing the processing loop, and the totals are correct.

Check your understanding

  1. What does 'program to an interface' mean?

    Show answer

    Declare variables and parameters using an interface type so any implementation can be used.

  2. What is a sign that behaviour should move into an overridden method?

    Show answer

    Long chains of instanceof checks that do different things for each type.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.