I understand that an interface is a contract for classes and that if a class implements an interface, then all methods in the interface must be in the class.
Here is an example involving interfaces from this question that confuses me:
public class Contact implements Comparable<Contact> {
private String name;
public int compareTo(Contact other) {
return name.compareTo(other.name);
}
}
You can then obviously create an ArrayList
and sort it by name.
List<Contact> contacts = new ArrayList<Contact>();
Collections.sort(contacts);
But if Contract
does not implement Comparable
like so:
public class Contact {
private String name;
public int compareTo(Contact other) {
return name.compareTo(other.name);
}
}
Calling Collections.sort
will give a compile time error even though the compareTo
method still exists.
Clearly there can be additional functionality provided by implementing interfaces. What is the purpose of interfaces other than for enforcing structure?