Interfaces and Polymorphism
Adding commands without modifying the processor
13.1 Learning Objectives
By the end of this chapter, you should be able to:
- define a contract using
interface; - implement the same contract in different classes;
- use references typed to the interface;
- explain dynamic dispatch;
- add behavior without editing a chain of conditionals.
13.2 Command Contract

Figure 13.1. Different implementations fulfill the same contract.
An interface describes what an object offers without imposing a state hierarchy:
interface Command {
String name();
String execute();
}
Different classes can implement the contract:
final class HelpCommand implements Command {
@Override
public String name() {
return "help";
}
@Override
public String execute() {
return "Commands: help and tip.";
}
}
final class TipCommand implements Command {
@Override
public String name() {
return "tip";
}
@Override
public String execute() {
return "Program to small contracts.";
}
}
13.3 Polymorphism at Runtime
import java.util.List;
interface Command {
String name();
String execute();
}
final class HelpCommand implements Command {
public String name() {
return "help";
}
public String execute() {
return "Commands: help and tip.";
}
}
final class TipCommand implements Command {
public String name() {
return "tip";
}
public String execute() {
return "Program to small contracts.";
}
}
public class Chapter13Polymorphism {
static String process(String input, List<Command> commands) {
for (Command command : commands) {
if (command.name().equalsIgnoreCase(input)) {
return command.execute();
}
}
return "Unknown command.";
}
public static void main(String[] args) {
List<Command> commands =
List.of(new HelpCommand(), new TipCommand());
System.out.println(process("tip", commands));
}
}
The list stores different objects through the same contract. When execute() is called, the JVM selects the implementation belonging to the concrete object. That is dynamic dispatch.
13.4 Interface or Abstract Class?
Prefer an interface when the focus is a role that different classes can play. Use an abstract class when subclasses genuinely share state and implementation.
A class can implement multiple interfaces, but it can extend only one class.
13.5 Project Evolution: Version 13
Each command becomes an object. To add AboutCommand, create a new class and register an instance; the core processing logic remains unchanged.
The complete example is in examples/src/Chapter13Polymorphism.java.
13.6 Verifiable Practice
- Implement
AboutCommand. - Add it to the list.
- Confirm that
processwas not modified. - Create a test implementation that always returns
"OK".
Test cases:
| Input | Implementation called |
|---|---|
help | HelpCommand |
TIP | TipCommand |
xyz | none; default response |
Sign of useful polymorphism
The consuming code knows the
Commandcontract, not a sequence of checks for each concrete class.