Lesson 10 of 23
In progress
Polymorphism in practice
Call the same method on different objects, understand dynamic dispatch, and avoid the instanceof chains that polymorphism replaces.
Polymorphism means one call, several behaviours. It is the mechanism that lets you write a loop over a list of shapes without knowing which shape each element is.
What you will learn
- Call overridden methods through a supertype.
- Predict which method runs at runtime.
- Replace type-checking chains with a common method.
Dispatch
public class Zoo {
interface Animal {
String sound();
}
static class Dog implements Animal {
public String sound() { return "woof"; }
}
static class Cat implements Animal {
public String sound() { return "meow"; }
}
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Dog() };
for (Animal animal : animals) {
System.out.println(animal.sound());
}
}
}
The array holds Animal references, and each call to sound() runs the implementation belonging to the object’s actual class. The compiler checks that Animal has a sound() method; the runtime picks which body to run. That is dynamic dispatch.
The alternative is a loop with type tests, which the compiler cannot check for completeness and which grows with every new subtype.
The chain that polymorphism replaces
static String sound(Object animal) {
if (animal instanceof Dog) {
return "woof";
} else if (animal instanceof Cat) {
return "meow";
}
return "unknown";
}
Adding a Cow means editing this method, and forgetting to do so produces "unknown" rather than a compile error. With a common interface plus an override, adding Cow means implementing sound once, and the loop needs no change.
The rule of thumb: if a method’s body is a chain of instanceof checks on its own parameter, the behaviour belongs on those types.
The declared type and the actual type
Animal a = new Dog();
a.sound(); // woof
The declared type decides what compiles; the actual type decides what runs. a cannot call a method that only Dog has:
// a.fetch(); // compile error, Animal has no fetch
To call a subtype-specific method, cast:
if (a instanceof Dog dog) {
dog.fetch();
}
That is a pattern match, and it is the modern way to write a checked cast. The variable dog is in scope only inside the branch, so the cast cannot be used where it would be unsafe.
Polymorphism with parameters
static long totalArea(java.util.List<Shape> shapes) {
long total = 0;
for (Shape shape : shapes) {
total += Math.round(shape.area() * 100);
}
return total;
}
This method works for every current and future Shape. It depends only on the contract, which is the definition of good abstraction: the code does not need to know what it is operating on.
The contract matters. If one shape’s area() returns a negative value, totalArea is wrong and every implementation is suspect. Polymorphism distributes responsibility, and with it the obligation to honour the interface.
Overloading versus overriding
- Overloading: same name, different parameters, resolved at compile time by the static types.
- Overriding: same signature, subclass replaces behaviour, resolved at runtime by the object’s class.
static void print(Animal a) { System.out.println("animal"); }
static void print(Dog d) { System.out.println("dog"); }
Animal a = new Dog();
print(a); // "animal", because the declared type is Animal
That result surprises people. Overload selection uses the compile-time type, so a variable declared as Animal picks the Animal overload even when it holds a Dog. Overriding is the mechanism to rely on; overloads with related types are a trap.
Polymorphism through interfaces
The interface is the contract, and any class can implement it, including classes that share no inheritance:
interface Exportable {
String toCsv();
}
class Invoice implements Exportable {
public String toCsv() { return "invoice," + 1250; }
}
class Customer implements Exportable {
public String toCsv() { return "customer,Ana"; }
}
A method that takes List<Exportable> can export both, with no knowledge of invoices or customers. That is more flexible than a base class, because the two types need not be related.
When polymorphism is the wrong tool
If there is exactly one implementation and no prospect of another, an interface plus one class adds a layer for nothing. If the variation is data rather than behaviour — a table of rates — a map or a config value is simpler than a subclass per rate.
The signal that polymorphism fits: a growing set of types that all answer the same question, and a caller that wants to treat them uniformly.
Declaring a variable as the subtype and then wondering why a method from the supertype is not used. Dispatch works on the object, but overload selection works on the declared type; keeping variables at the interface level avoids the confusion.
Define an interface Priced with a method pricePaise(). Implement it for a book and a course, then write a method that takes a list and returns the total. Show that the method needs no type checks.
Show solution
import java.util.List; public class Cart { interface Priced { long pricePaise(); } record Book(String title, long pricePaise) implements Priced {} record Course(String name, long pricePaise) implements Priced {} static long total(List<Priced> items) { long sum = 0; for (Priced item : items) { sum += item.pricePaise(); } return sum; } public static void main(String[] args) { List<Priced> items = List.of( new Book("Small Systems", 45_000L), new Course("SQL", 129_900L) ); System.out.println(total(items) / 100.0); } } Records can implement interfaces, so both types satisfy Priced without sharing a superclass. total depends only on the method it calls, and a third type would need no change to it.
Recap
- The declared type controls what compiles; the object’s class controls which override runs.
- Replace
instanceofchains with a common method on the types themselves. - Overloads resolve at compile time, so avoid them for related subtypes.
Next, interfaces: contracts without implementation, default methods, and functional shapes.
Can an interface have fields?
What is a functional interface?
Progress is saved in this browser only. No account, no email.