Interfaces in the Wild
The first situations where you’ll want to use interfaces involve applying pre-defined interfaces and classes that are part of Java. Here are a few examples.
Purpose: A class implements
Comparable<T> in order to allow comparison—in a “greater than” and “less than” sense—to another instance of the class. This is a “parameterized” interface, which means that you need to specify the class that it will be comparing. For example,
Comparable<Job> would compare
Purpose: Compares two objects of a given class. To allow comparisons and ordering based on the different fields, you can create several different
Comparator classes. The class for the compared objects does NOT implement the interface itself.
This interface can be used to determine, given two objects of the given type, which one is “greater” than the other. It is also used by collections such as an
ArrayList to sort its contents with the
For more on the differences between Comparator and Comparable, see this article .
Purpose: Enables iteration over a collection of objects using a for-each loop
This interface is implemented by the
ArrayList<T> class, which we’ve been using throughout this course.
Purpose: Enables access to objects in a collection by index. In other words, it enables ordered collections.
This interface is also implemented by the
ArrayList<T> class, which we’ve been using throughout this course. In fact,
Iterable<T>. An interface may extend another interface, in the same way that classes may extend each other.
Purpose: Represents a collection of key/value pairs.
This interface is implemented by theHashMap<K, V>` class, which we’ve been using throughout this course.
Check Your Understanding
True/False: An interface can extend another interface.