Interface

An interface is a named contract — a list of method signatures that any implementing class must fulfil. Interfaces are Java's primary mechanism for polymorphism and for decoupling code from concrete implementations.

Example

public interface Shape {
    double area();
    double perimeter();
}

public class Circle implements Shape {
    private final double r;
    public Circle(double r) { this.r = r; }
    @Override public double area()      { return Math.PI * r * r; }
    @Override public double perimeter() { return 2 * Math.PI * r; }
}

Default methods (Java 8+)

Interfaces can provide a default implementation that classes inherit unless they override it:

public interface Greeter {
    String name();
    default String greet() { return "Hello, " + name(); }
}

Functional interfaces

An interface with exactly one abstract method is a functional interface and can be implemented with a lambda:

Runnable r = () -> System.out.println("running");
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());

Multiple interface inheritance

A class can implement any number of interfaces. This is how Java provides multiple inheritance of behaviour contracts without the "diamond problem" of multiple class inheritance.

See the full interface guide.