Card 02/ 08

ExampleDifficulty: Intermediate1 min

Interfaces Example: An Invoice That Implements Comparable

A list of invoices sorted by a library method that has never seen the Invoice class.

Implementing a standard interface lets existing library code work with your class. Comparable has one method, compareTo, and any class that implements it can be sorted by Collections.sort, which was written long before your class existed:

java
class Invoice implements Comparable<Invoice> {
    LocalDate due;

    @Override
    public int compareTo(Invoice other) {
        return due.compareTo(other.due);
    }
}
java
List<Invoice> invoices = new ArrayList<>(loadInvoices());
Collections.sort(invoices);

Collections.sort knows nothing about invoices, due dates or billing. It knows that whatever it has been handed implements Comparable, so each element can answer one question: are you before or after this other one.

Notice the direction of the dependency. The library did not have to be changed to support Invoice; Invoice declared that it meets a capability the library already required. New code plugs into old code, which is the opposite of how it usually goes.