Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection
. However, each JDBC driver provides its own implementation of Connection
. You don't have to know anything about the particular implementation, because it conforms to the Connection
interface.
Another one is from the java collections framework. There is a java.util.Collection
interface, which defines size
, add
and remove
methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList
because it's more efficient for it's purposes, and the other uses a TreeSet
.
Because both LinkedList
and TreeSet
implement the Collection
interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size()
method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection
interface, rather than to LinkedList
and TreeSet
in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.