An interfaces defines a contract. Any class that implements an interface has to fulfil that contract. This means that the class must implement methods defined in the interface.
An interface basically says "I'm defining something that all implementers must do. I don't care how you do it, but you must support these operations that I've specified".
Another use of interfaces is that you can use them in method signatures or type definitions to specify the most generic type of an object. For example, in Java Map
is an interface that is implemented by other classes like HashMap
or LinkedHashMap
. Both HashMap
and LinkedHashMap
are essentially of type Map
. They implement the same methods, but they do things differently (LinkedHashMap
preserves insertion-order).
Consider the situation where you have a method that accepts maps. If you didn't have interfaces, you would need to specify a method for each type of map. Indeed, you could do that via overloaded methods, but that approach is not very good. The better way is to specify the type of the method argument as Map
. Then, any class that implements Map
can be passed in to the method. This way, you don't have to specify a method for each type of map, and also you are not restricting the person who uses your method, to specific implementations of the map.
An interface also guarantees that the specified functionality is present in implementing classes. As such, it also provides a standard way to access that functionality. Interfaces are also useful when you are designing an API (that way you can specify a standard interface to the things you want to expose).
Another benefit of interfaces is that it makes refactoring easy. Let's say that you want to switch out an implementation of a some sort of object. The object might be a method argument or it may be a class property. Since you've typed that argument or object as an interface, you can simply create a new class that implements the interface and pass that class instead. Since you used the interface, you didn't make an extra assumptions as to the details of the class. The interface abstracts out the implementation details of the class that you're using. That way you don't end up making assumptions that makes your code too tightly-coupled to a specific implementation.
To sum it up, interfaces are about abstraction and contracts. With abstraction you hide the underlying details and expose only the bare minimum that you need to expose. That way the person who uses your class or interface is not burdened with the implementation details. All that information is neatly hidden inside the specific class that implements the interface. The contract ensures standardization across the board; a person who uses the interface is sure that all classes that implement the interface expose the same methods.