Lesson 5 of 9
Polymorphism - One Interface, Many Forms
Polymorphism lets you write code that works with objects of many types through a common interface. The same method call behaves differently depending on the actual runtime type of the object. This is the mechanism that makes collections of mixed types and plugin architectures possible.
Compile-Time vs Runtime Polymorphism
- Compile-time (Static) polymorphism = method overloading. Resolved at compile time by parameter types.
- Runtime (Dynamic) polymorphism = method overriding via inheritance/interface. JVM decides which version to call based on the ACTUAL object type at runtime.
- Upcasting: assign a subclass to a superclass/interface reference - automatic (widening).
- Downcasting: cast a reference back to its subtype - explicit, may throw ClassCastException.
- instanceof: check type before casting. Java 16+ pattern matching makes this concise.
Polymorphism in a Library Checkout
import java.util.List;
public class LibraryCheckoutService {
// Works with ANY LibraryItem subclass - polymorphism in action
public void processCheckout(LibraryItem item, String memberId) {
if (item.borrow()) {
System.out.printf("✓ %s checked out '%s'%n", memberId, item.getTitle());
} else {
System.out.printf("✗ '%s' is not available%n", item.getTitle());
}
}
// Process a whole catalog - different types, same loop
public void generateCatalogReport(List<LibraryItem> items) {
System.out.println("=== CATALOG REPORT ===");
for (LibraryItem item : items) {
// Calls the correct getDisplaySummary() at runtime
System.out.println(item.getDisplaySummary());
// Pattern matching instanceof (Java 16+) - safe downcasting
if (item instanceof Book book) {
// book is automatically cast - no separate cast needed
System.out.printf(" -> Late fee: $%.2f/day%n", book.calculateLateFee(1));
} else if (item instanceof EBook ebook) {
System.out.printf(" -> Download: %s%n", ebook.getDownloadUrl());
} else if (item instanceof AudioBook audio) {
System.out.printf(" -> Runtime: %d min%n", audio.getRuntimeMinutes());
}
}
}
public static void main(String[] args) {
// All stored as LibraryItem - mixed list
List<LibraryItem> catalog = List.of(
new Book("001", "Clean Code", "Robert Martin", 39.99),
new EBook("002", "Effective Java", "https://example.com/ej.epub", 3),
new AudioBook("003", "The Pragmatic Programmer", "Various", 540)
);
var service = new LibraryCheckoutService();
// processCheckout works the same for all types
catalog.forEach(item -> service.processCheckout(item, "MBR-001"));
service.generateCatalogReport(catalog);
}
}Quick Quiz
Tip
Tip
Practice Polymorphism One Interface Many Forms in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Polymorphism - One Interface, Many Forms
Practice Task
Note
Practice Task - (1) Write a working example of Polymorphism One Interface Many Forms from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Polymorphism One Interface Many Forms is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- Polymorphism lets you write code that works with objects of many types through a common interface.
- Compile-time (Static) polymorphism = method overloading. Resolved at compile time by parameter types.
- Runtime (Dynamic) polymorphism = method overriding via inheritance/interface. JVM decides which version to call based on the ACTUAL object type at runtime.
- Upcasting: assign a subclass to a superclass/interface reference - automatic (widening).
Finished this lesson?