Card 01/ 08
Java Interfaces: Naming a Capability Without an Implementation
An archiving job that handles invoices, staff records and files without knowing which it has.
An interface is a named list of method signatures with no bodies. A class that declares implements followed by the interface's name promises to supply those methods, and code written against the interface then works with any class that makes the promise.
An archiving job has to handle invoices, staff records and uploaded files. It does not care which it has; it only needs each one to give a key to file it under and to say whether it has expired. An interface is a name for exactly that capability and nothing else:
interface Archivable {
String archiveKey();
boolean isExpired();
}A class that writes implements Archivable is promising those two methods exist. The compiler enforces the promise: leave one out and the class will not build.
A variable can be declared with an interface type, Archivable item, and hold an invoice one moment and a file the next.
| The interface decides | The class decides |
|---|---|
| Which methods exist, and their signatures | What each method does |
| That anything implementing it can be used interchangeably | What state it keeps to do the job |
So code written against Archivable works with every class that ever implements it, including ones written after that code shipped. That is the payoff: the calling code names a capability rather than a list of types, and the list of types is free to grow.
← → move through sections and cards