Java Polymorphism: One Method Call, Different Behaviour (Beginner)

31 December 2026 javatypescriptbeginners
PDF The design sheet The full architecture and the verified references. Free, no email.
Thumbnail for Java Polymorphism: One Method Call, Different Behaviour (Beginner) 6:52
Watch on YouTube, or read on below.
Run this yourself → Clone the repo, docker compose up, and watch it happen

The shop takes card and cash, and now vouchers too. Does checkout need another if every time a payment type is added?

Asking what kind of payment it is

int totalFor(String type, int priceCents) {
    if (type.equals("card")) {
        return priceCents + priceCents * 2 / 100;
    }
    if (type.equals("cash")) {
        return priceCents;
    }
    throw new IllegalArgumentException("unknown payment type: " + type);
}

Card and cash print 1020 and 1000; voucher throws unknown payment type: voucher. An if statement is not wrong, and for two fixed types it may be the simplest thing. But every new payment type means editing this method.

Letting the object answer

int totalFor(PaymentMethod method, int priceCents) {
    return method.totalCents(priceCents);
}

The same job, the same answer: 1020 and 1000. Last episode’s VoucherPayment (a fixed 50 cent fee) gives 1050. We still created the class and passed it in, but the checkout calculation did not change.

One variable, two objects

A PaymentMethod variable holding a card prints 1020; given a cash payment, the identical call prints 1000. The variable is still a PaymentMethod; the object changed. Every payment uses the same inherited totalCents, and inside it Java calls the feeCents belonging to the actual object. That is polymorphism: the same call through a shared type, different objects, different behaviour.

TypeScript

The same abstract class, three payment types and a totalFor function print 1020, 1000 and 1050.

The challenge

Add a fourth payment type, with any fee, without changing totalFor. Next episode: records, a class whose only job is to hold data.


Watch next

New videos land on Code with Sam - subscribe there if this was useful.

Get the interview pack

A free, practical pack for engineers preparing for senior backend interviews - the questions that actually get asked, and how to answer them like someone who has done the work.

New articles and videos when they land. No spam, and one click to leave.