JAVA-102 · Lesson 7 of 12 · 23 min
Polymorphism in practice
▶ Video coming soon A video version of this lesson is on the way.
Lessons 5 and 6 built a family of booking types. The plan for Wednesday, March 3, 2027 is to use that family the way it was designed to be used. Hamza's first draft of the day sheet, the page Tamsin will print each morning, had a long if-else chain asking each booking what kind it was and then working out its price and summary differently for each kind. Ingrid's comment on the draft is one word: polymorphism. This lesson shows why one call such as b.summary() can replace the whole chain, and when the newer pattern-matching switch is the better tool.
One call, many behaviors
Polymorphism, from the Greek for "many forms", means that one variable of a general type can refer to objects of many specific types, and calling a method on it runs the version belonging to the actual object. A variable of type Booking can hold a RepairBooking or a RentalBooking. When the program calls b.priceCents(), Java looks at the object b refers to while the program runs and calls that class's priceCents. This choice made at run time is called dynamic dispatch or late binding.
public class Main {
public static void main(String[] args) {
Booking[] sheet = {
new RepairBooking("Ana Ruiz", "brake bleed", 4500),
new RentalBooking("Theo Park", 3),
new RepairBooking("Mei Lin", "full tune-up", 8500),
new RentalBooking("Ravi Shah", 7),
};
long total = 0;
for (Booking b : sheet) {
System.out.printf("%-10s %-24s %6d%n", b.getCustomer(), b.summary(), b.priceCents());
total += b.priceCents();
}
System.out.println("Day total: " + total + " cents");
}
}
abstract class Booking {
private final String customer;
Booking(String customer) { this.customer = customer; }
String getCustomer() { return customer; }
abstract String summary();
abstract long priceCents();
}
class RepairBooking extends Booking {
private final String job;
private final long quote;
RepairBooking(String c, String job, long quote) { super(c); this.job = job; this.quote = quote; }
@Override String summary() { return "repair: " + job; }
@Override long priceCents() { return quote; }
}
class RentalBooking extends Booking {
private final int days;
RentalBooking(String c, int days) { super(c); this.days = days; }
@Override String summary() { return "rental: " + days + " day(s)"; }
@Override long priceCents() { return 1500L * (days - days / 7); }
}Ana Ruiz repair: brake bleed 4500 Theo Park rental: 3 day(s) 4500 Mei Lin repair: full tune-up 8500 Ravi Shah rental: 7 day(s) 9000 Day total: 26500 cents
What this code does
The loop variable b has the type Booking, but each object it refers to is a repair or a rental. Each call to summary and priceCents runs the version of the object's own class, so the loop needs no if statements about kinds. Adding a third kind of booking would need no change to this loop.
Declared type and actual type
Every reference has two types worth keeping apart. The declared type, also called the static type, is the type written in the variable's declaration, such as Booking. It decides which methods javac lets you call: only methods that Booking has. The actual type, or run-time type, is the class of the object the variable refers to at that moment. It decides which version of the method runs. A Booking variable holding a RentalBooking cannot call getDays(), because Booking has no getDays, even though the object does.
public class Main {
public static void main(String[] args) {
Booking b = new RentalBooking("Theo Park", 3);
System.out.println(b.getDays());
}
}
abstract class Booking {
abstract String summary();
}
class RentalBooking extends Booking {
private final int days;
RentalBooking(String c, int days) { this.days = days; }
int getDays() { return days; }
@Override String summary() { return "rental"; }
}What this code does
The declared type of b is Booking, and Booking has no getDays method, so javac reports that it cannot find the symbol. The object really is a RentalBooking, but javac checks calls against the declared type only. To use getDays, the program must first check that the object is a rental, as the next section shows.
$ javac Main.java
Main.java:4: error: cannot find symbol
System.out.println(b.getDays());
^
symbol: method getDays()
location: variable b of type Booking
1 errorAssigning a RentalBooking to a Booking variable is an upcast, and it is always safe, so Java does it automatically. Going the other way, from Booking to RentalBooking, is a downcast, which might be wrong, so it needs an explicit check.
instanceof and pattern matching
The instanceof operator tests whether an object is an instance of a type. Since Java 16 it can also declare a variable of that type in the same step, a feature called pattern matching for instanceof. The old style needed a separate cast; the new style is shorter and cannot get the cast wrong.
public class Main {
public static void main(String[] args) {
Booking[] all = {
new RepairBooking("Ana Ruiz", "brake bleed"),
new RentalBooking("Theo Park", 3),
};
for (Booking b : all) {
// old style: test, then cast
if (b instanceof RentalBooking) {
RentalBooking r = (RentalBooking) b;
System.out.println("Old style: " + r.getDays() + " days");
}
// pattern matching: test and bind in one step
if (b instanceof RentalBooking r && r.getDays() > 2) {
System.out.println("Long rental for " + b.getCustomer() + ": helmet check needed");
}
}
}
}
abstract class Booking {
private final String customer;
Booking(String c) { customer = c; }
String getCustomer() { return customer; }
}
class RepairBooking extends Booking {
private final String job;
RepairBooking(String c, String job) { super(c); this.job = job; }
}
class RentalBooking extends Booking {
private final int days;
RentalBooking(String c, int days) { super(c); this.days = days; }
int getDays() { return days; }
}Old style: 3 days Long rental for Theo Park: helmet check needed
What this code does
The first if uses the classic pattern: test with instanceof, then cast to reach getDays. The second binds r in the instanceof test itself, and r can be used in the rest of the condition because the && only evaluates it when the test succeeded. Both skip the repair booking.
A cast to the wrong type compiles but fails when it runs, with a ClassCastException. Pattern matching avoids that, because the variable exists only when the test has succeeded.
public class Main {
public static void main(String[] args) {
Object thing = "brake bleed";
Integer n = (Integer) thing;
System.out.println(n);
}
}What this code does
thing holds a String, but the cast claims it is an Integer. javac accepts the cast because an Object might be an Integer, but the JVM checks when the line runs and throws ClassCastException. Testing with instanceof first, or using a pattern, prevents this.
$ javac Main.java
$ java Main
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
at Main.main(Main.java:4)When instanceof chains are a design smell
If you find yourself writing if (b instanceof RepairBooking) ... else if (b instanceof RentalBooking) ... to choose what to do, ask whether the behavior belongs in the classes instead. If every kind of booking needs a price, priceCents should be a method each class overrides, and the chain disappears. The chain also has a hidden cost: when a third kind of booking is added, every chain in the program must be found and updated, and the compiler will not help.
There are honest exceptions. Sometimes the operation does not belong in the classes, for example formatting bookings for one particular report, and putting a method for every report into Booking would make it bloated. For those cases, Java 21 offers a better tool than an if chain.
Pattern matching for switch
Since Java 21 a switch can test types, with type patterns in its case labels. Each case names a type and a variable, and the variable has that type inside the case. When the selector's type is a sealed interface or class, javac knows every permitted subtype and checks that the switch covers them all, so no default is needed. If a new permitted type is added later, every switch that misses it stops compiling, which is exactly the help the if chain could not give.
public class Main {
public static void main(String[] args) {
Booking[] all = {
new RepairBooking("Ana Ruiz", "brake bleed", 45),
new RentalBooking("Theo Park", 3, true),
new RentalBooking("Mei Lin", 1, false),
};
for (Booking b : all) {
System.out.println(tagLine(b));
}
}
static String tagLine(Booking b) {
return switch (b) {
case RepairBooking r -> "REPAIR " + r.customer() + ", " + r.job() + ", " + r.minutes() + " min";
case RentalBooking r when r.helmet() -> "RENTAL " + r.customer() + ", " + r.days() + " d, helmet out";
case RentalBooking r -> "RENTAL " + r.customer() + ", " + r.days() + " d";
};
}
}
sealed interface Booking permits RepairBooking, RentalBooking {
String customer();
}
record RepairBooking(String customer, String job, int minutes) implements Booking { }
record RentalBooking(String customer, int days, boolean helmet) implements Booking { }REPAIR Ana Ruiz, brake bleed, 45 min RENTAL Theo Park, 3 d, helmet out RENTAL Mei Lin, 1 d
What this code does
The switch tests the type of b and binds r with the right type in each case, so r.job() and r.days() can be called directly. The when clause adds a condition to a case, so rentals with a helmet get a different line. Booking is sealed, so javac can check that the cases cover every permitted type and no default is needed.
The two bookings are written as records, the compact data classes JAVA-101 previewed and lesson 9 explains fully. Records and sealed interfaces work especially well together: the interface lists the kinds, each record holds the data for its kind, and switches handle them.
Record patterns
Java 21 also allows record patterns, which take a record apart in the case label itself. Instead of binding r and calling r.days(), the case can name the record's components directly. Patterns can nest, and var lets javac infer a component's type.
public class Main {
public static void main(String[] args) {
Booking[] all = {
new RepairBooking("Ana Ruiz", "brake bleed", 45),
new RentalBooking("Theo Park", 8, true),
new RentalBooking("Mei Lin", 2, false),
};
long total = 0;
for (Booking b : all) {
long price = switch (b) {
case RepairBooking(var who, var job, int minutes) -> 4000L * minutes / 60;
case RentalBooking(var who, int days, boolean helmet) -> 1500L * (days - days / 7) + (helmet ? 300 : 0);
};
System.out.println(b.customer() + ": " + price + " cents");
total += price;
}
System.out.println("Total: " + total + " cents");
}
}
sealed interface Booking permits RepairBooking, RentalBooking {
String customer();
}
record RepairBooking(String customer, String job, int minutes) implements Booking { }
record RentalBooking(String customer, int days, boolean helmet) implements Booking { }Ana Ruiz: 3000 cents Theo Park: 10800 cents Mei Lin: 3000 cents Total: 16800 cents
What this code does
Each case takes the record apart into named variables, so the price formula can use minutes or days directly. A repair is charged 40 dollars an hour for its minutes, and a rental 15 dollars a day with every seventh day free, plus 3 dollars for a helmet. The switch is an expression that produces the price, and it covers both permitted types.
| Approach | Good for | Weakness |
|---|---|---|
| Overridden methods (dynamic dispatch) | Behavior that every kind needs and that belongs to the objects | Every new operation means a method in every class |
| instanceof if-else chain | A quick one-off check | No help from javac when a new kind is added |
| switch with type patterns over a sealed type | Operations outside the classes, such as reports | Every switch must change when a kind is added, though javac finds them |
Polymorphic parameters and the substitution rule
Methods gain the same benefit as loops. A method whose parameter is the general type, such as printReceipt(Priced item), works with every class that implements Priced, now and in the future. Programming against the general type rather than a specific class is often summed up as program to an interface.
For this to work, every subclass must honor the promises of its superclass. If code that works with a Booking works with any Booking, a subclass must not break it: it must not throw from a method the superclass promises always works, or demand stricter inputs, or return weaker results. This is the Liskov substitution principle, named after the computer scientist Barbara Liskov. A subclass that breaks it, such as a FreeRentalBooking whose priceCents throws an exception, should not be a subclass.
public class Main {
public static void main(String[] args) {
Priced[] items = {
new Item("700x25c inner tube", 899),
new Item("brake pads", 1650),
new RentalPrice(3),
};
for (Priced p : items) {
printLine(p);
}
System.out.println("Most expensive: " + mostExpensive(items).label());
}
static void printLine(Priced p) {
System.out.printf("%-22s %6d%n", p.label(), p.priceCents());
}
static Priced mostExpensive(Priced[] items) {
Priced best = items[0];
for (Priced p : items) {
if (p.priceCents() > best.priceCents()) best = p;
}
return best;
}
}
interface Priced {
long priceCents();
String label();
}
record Item(String label, long priceCents) implements Priced { }
record RentalPrice(int days) implements Priced {
public long priceCents() { return 1500L * days; }
public String label() { return "city bike, " + days + " days"; }
}700x25c inner tube 899 brake pads 1650 city bike, 3 days 4500 Most expensive: city bike, 3 days
What this code does
printLine and mostExpensive take Priced parameters, so they work with items, rentals and any future Priced type. Each record satisfies the interface in its own way: Item's components already have the right names, while RentalPrice works its values out. mostExpensive returns a Priced, and the caller asks it for its label.
Here a record named Item implements Priced simply by having components named label and priceCents: a record's accessor methods are public, so they satisfy the interface. Lesson 9 returns to this.
Try it yourself
Replace the chain
The starter decides each job's minutes with an instanceof chain in main. Replace the chain with polymorphism: add an abstract method minutes() to Job and override it in each subclass (FlatRepair 20, TuneUp 60, BrakeBleed 45).
The program should still print flat repair 20, tune-up 60, brake bleed 45 and Total: 125.
public class Main {
public static void main(String[] args) {
Job[] jobs = { new FlatRepair(), new TuneUp(), new BrakeBleed() };
int total = 0;
for (Job j : jobs) {
int m;
if (j instanceof FlatRepair) m = 20;
else if (j instanceof TuneUp) m = 60;
else m = 0;
System.out.println(j.name() + " " + m);
total += m;
}
System.out.println("Total: " + total);
}
}
abstract class Job {
abstract String name();
}
class FlatRepair extends Job { @Override String name() { return "flat repair"; } }
class TuneUp extends Job { @Override String name() { return "tune-up"; } }
class BrakeBleed extends Job { @Override String name() { return "brake bleed"; } }Try it yourself
A switch over a sealed type
Complete deposit(Rental r) with a switch over the sealed interface Rental so a CityBike needs a 2500 cent deposit, a CargoBike 10000 and a Tandem 7500.
The program should print City bike 4: 2500, Cargo bike 1: 10000 and Tandem: 7500.
public class Main {
public static void main(String[] args) {
Rental[] fleet = { new CityBike(4), new CargoBike(1), new Tandem() };
for (Rental r : fleet) {
System.out.println(r.name() + ": " + deposit(r));
}
}
static long deposit(Rental r) {
return 0;
}
}
sealed interface Rental permits CityBike, CargoBike, Tandem {
String name();
}
record CityBike(int number) implements Rental {
public String name() { return "City bike " + number; }
}
record CargoBike(int number) implements Rental {
public String name() { return "Cargo bike " + number; }
}
record Tandem() implements Rental {
public String name() { return "Tandem"; }
}Common mistakes
MistakeWriting an instanceof chain to choose behavior that every kind needs.
InsteadPut the behavior in an overridden method so each class supplies its own.
MistakeCalling a subclass-only method through a superclass variable.
InsteadCheck the type with a pattern, such as b instanceof RentalBooking r, and call it on r.
MistakeCasting without checking, as (RentalBooking) b.
InsteadA wrong cast throws ClassCastException; use instanceof or a pattern first.
MistakeAdding a default case to a switch over a sealed type out of habit.
InsteadLeave it out so javac reports any permitted type you have not handled.
MistakeWriting a subclass whose method throws where the superclass promises a result.
InsteadA subclass must be usable wherever its superclass is; if it cannot, it should not be a subclass.
Summary and key terms
- Polymorphism lets one variable of a general type refer to objects of many specific types, and a method call runs the version of the object's own class, chosen at run time by dynamic dispatch.
- The declared type decides which methods javac allows; the actual type decides which version runs.
- Upcasts are automatic and safe; downcasts need a check, and a wrong cast throws ClassCastException.
- Pattern matching for instanceof tests and binds a variable in one step.
- Chains of instanceof tests usually mean behavior belongs in the classes.
- Since Java 21, switch can match types with patterns, add conditions with when and take records apart with record patterns, and over a sealed type javac checks that every permitted case is covered.
- Parameters of a general type make methods work with future classes, provided every subtype keeps its supertype's promises, the Liskov substitution principle.
- Polymorphism
- One variable or call working with objects of many types, each answering in its own way.
- Dynamic dispatch
- Choosing which method version runs from the object's class while the program runs.
- Declared type
- The type written for a variable, which decides which methods may be called.
- Actual type
- The class of the object a variable refers to at run time.
- Upcast
- Treating an object as one of its supertypes; always safe.
- Downcast
- Treating an object as one of its subtypes; needs a check.
- instanceof
- An operator that tests whether an object is an instance of a type.
- Type pattern
- A pattern, such as RentalBooking r, that tests a type and binds a variable.
- Record pattern
- A pattern that takes a record apart into its components.
- Liskov substitution principle
- The rule that a subtype must be usable wherever its supertype is expected.
- ClassCastException
- The exception thrown when a cast names the wrong type.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which type decides whether javac allows a method call, and which decides which version runs?
Show answer
The declared type allows the call; the actual type decides the version.
Why does b.getDays() fail to compile when b is declared as Booking?
Show answer
Booking has no getDays method, and javac checks against the declared type.
What does b instanceof RentalBooking r do?
Show answer
Tests whether b is a RentalBooking and, if so, binds r to it as a RentalBooking.
Why can a switch over a sealed interface leave out default?
Show answer
javac knows every permitted subtype and checks that the cases cover them all.
What does the Liskov substitution principle require of a subclass?
Show answer
That it can be used anywhere its superclass is expected without breaking the code.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.