Java interfaces: what is an interface and when are they used?

In Java, an interface is a "blueprint" that defines which methods are common to some group of classes. We can then write code that operates on instances of that interface without having to know the specific class in question. In other words, the purpose of interfaces is generally to allow us to write more flexible code. By using interfaces, we can avoid duplication or having to write methods that would otherwise only work on specific classes of objects.

For example, one common example of an interface is the List interface (defined in the standard java.util package). An interface is declared in a similar way to a class (in fact, it is very similar to an abstract class), but generally includes a list of method signatures without implementations (in other words, abstract methods). In addition, all methods in an interface are assumed to be public. Part of the definition of the List interface looks as follows:

public interface List<T> {

    int size();
	
    boolean contains(Object o);

}

Any number of other classes can be defined to implement List. For example, the Java classes LinkedList, ArrayList, Stack and CopyOnWriteArrayList all implement List. Because these classes are defined as implementing List, this means in effect that they "promise" that they have definitions of size() and contains() (and other methods of the List interface).

Creating an object that implements a given interface

To create an object that implements a given interface, we essentially have two choices: