EMZETT.
Login

Interface

In short: A contract that specifies WHICH methods a class must offer, without prescribing HOW these methods are implemented internally.

In more detail: A class that “implements” an interface commits to filling in all the methods defined in it with its own code. Unlike inheritance, a class can usually implement several interfaces at the same time, but inherit from only one single superclass — interfaces are thus a flexible way to enable polymorphism even between completely unrelated classes.

In Depth

interface Movable {
    void move();       // only the signature, NO implementation
}
 
class Car implements Movable {
    public void move() { System.out.println("Car starts driving"); }
}
class Bird implements Movable {
    public void move() { System.out.println("Bird starts flying"); }
}

Car and Bird have nothing in common in content and aren’t related to each other through inheritance — yet they can be treated uniformly thanks to the shared Movable interface:

List<Movable> things = List.of(new Car(), new Bird());
for (Movable m : things) {
    m.move();   // works for both, even though completely different classes
}

The central difference from an abstract class: an interface (in most languages and most cases) defines EXCLUSIVELY the “contract interface” — WHICH methods must exist — but no state of its own (fields) and traditionally no implementation. An abstract class, by contrast, can bring both already-finished methods and fields, and only leave part open. Some modern languages now also allow “default methods” with a default implementation directly in the interface, which somewhat blurs this boundary.

An interface is especially well suited for decoupling dependencies between parts of a program: a piece of code programmed only against an interface (instead of a concrete class) automatically works with ANY implementation of that interface — this makes it easier, for example, to swap a real database connection for a test stand-in (mock) in automated tests, without touching the actual application code.

See also: Abstraction, Polymorphism, Inheritance