Interfaces in Java

An interface defines what a type can do without saying how. Any class, record or enum can implement it, and code written against the interface works with all of them. Since Java 8, interfaces can also carry code in default and static methods, which changed how Java libraries evolve. This page explains what an interface can contain in each Java version, how conflicts between default methods are resolved, the rules javac enforces, and the special kinds: functional, marker and sealed interfaces.

Contents

What an interface is

An interface is a contract: a list of methods that implementing types promise to provide. List promises get, add and size; ArrayList and LinkedList keep that promise in different ways. Code that uses a List variable works with both, and with any future implementation. This is "programming to an interface", and it is the main reason interfaces exist.

A class can extend only one class but implement any number of interfaces, so interfaces are also how Java gives a type several roles: a String is a CharSequence, a Comparable<String> and a Serializable at once.

What an interface can contain, by Java version
MemberSinceNotes
Abstract methods1.0Implicitly public abstract
Constants1.0Every field is implicitly public static final
Nested types1.1Implicitly public static
default methods8Instance methods with a body that implementations inherit
static methods8Called through the interface name only
private methods9Helpers shared by default and static methods
sealed / permits17Restricts which types may implement the interface

What an interface still cannot have: instance fields, constructors, and protected or package-private members. Those are the reasons to choose an abstract class instead.

Abstract, default, static and private methods

The program defines a Shape interface that uses every kind of member: an abstract area, default methods that build on it, a static helper, a private formatting method and a constant. Two records implement it, and one of them overrides a default method.

Java
import java.util.List;

public class InterfaceFeatures {

    interface Shape {
        double PI_APPROX = 3.14;                 // implicitly public static final

        double area();                           // abstract: every shape must implement

        default String describe() {              // default (Java 8): shared implementation
            return name() + " with area " + format(area());
        }

        default String name() {
            return getClass().getSimpleName();
        }

        static Shape largest(List<Shape> shapes) {   // static (Java 8): a helper on the type
            Shape best = shapes.get(0);
            for (Shape s : shapes) {
                if (s.area() > best.area()) {
                    best = s;
                }
            }
            return best;
        }

        private String format(double value) {    // private (Java 9): helper for defaults
            return String.format("%.2f", value);
        }
    }

    record Circle(double r) implements Shape {
        @Override
        public double area() {
            return Math.PI * r * r;
        }
    }

    record Square(double side) implements Shape {
        @Override
        public double area() {
            return side * side;
        }

        @Override
        public String name() {                   // overriding a default method
            return "Square(" + side + ")";
        }
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1), new Square(2), new Circle(1.5));
        shapes.forEach(s -> System.out.println(s.describe()));
        System.out.println("largest: " + Shape.largest(shapes).name());
        System.out.println("constant: " + Shape.PI_APPROX);
    }
}

Output:

Output
Circle with area 3.14
Square(2.0) with area 4.00
Circle with area 7.07
largest: Circle
constant: 3.14
  • describe is written once, in the interface, and works for every shape because it calls the abstract area, which each record implements. Only area had to be written per type.
  • Square overrode the default name, so its line says "Square(2.0)"; the circles kept the default, which uses the class name.
  • Shape.largest is a static method: a helper that belongs with the type, called as Shape.largest(...). Before Java 8 such helpers lived in separate utility classes, such as Collections for Collection.
  • The private format method keeps the default methods short without becoming part of the public contract.
  • PI_APPROX is a constant. Interfaces used only to hold constants are considered an anti-pattern, because implementing them leaks the constants into the class's API; use a final class or an enum.

Why default methods were added

Before Java 8, adding a method to a published interface broke every class that implemented it. Java 8 needed to add methods such as forEach, removeIf and stream to Collection and Iterable without breaking thousands of existing collection classes. Default methods solved this: a new method can come with an implementation, and old classes inherit it. Iterable.forEach, Collection.removeIf, List.sort and Map.getOrDefault are all default methods.

The cost is that a class can now inherit code from several interfaces, so Java needs rules for conflicts. The program shows each rule.

Java
public class ResolutionRules {

    interface Named {
        default String name() {
            return "Named.name";
        }
    }

    // Rule 1: a method in a class (or superclass) wins over any default method
    static class Base {
        public String name() {
            return "Base.name";
        }
    }

    static class Child extends Base implements Named { }

    // Rule 2: a more specific interface wins over the one it extends
    interface Titled extends Named {
        @Override
        default String name() {
            return "Titled.name";
        }
    }

    static class Book implements Named, Titled { }

    // Rule 3: otherwise the class must override and may pick one with X.super.method()
    interface Labeled {
        default String name() {
            return "Labeled.name";
        }
    }

    static class Product implements Named, Labeled {
        @Override
        public String name() {
            return Labeled.super.name() + " (chosen explicitly)";
        }
    }

    public static void main(String[] args) {
        System.out.println("class wins:              " + new Child().name());
        System.out.println("more specific interface: " + new Book().name());
        System.out.println("conflict resolved:       " + new Product().name());
    }
}

Output:

Output
class wins:              Base.name
more specific interface: Titled.name
conflict resolved:       Labeled.name (chosen explicitly)
  1. The class wins. Child inherits name() from Base and a default name() from Named; the class method was used. This keeps old classes working when a default with the same signature is added to an interface they implement.
  2. The more specific interface wins. Titled extends Named and overrides its default, so Book, which implements both, got Titled's version.
  3. Otherwise the class must choose. Named and Labeled are unrelated, so Product would not compile without its own name(). Inside it, Labeled.super.name() calls a specific interface's default.

Multiple interfaces and functional interfaces

A duck both flies and swims: the program implements two interfaces whose defaults clash and combines them. It then defines a functional interface, an interface with exactly one abstract method, and builds a username validator by combining lambdas with a default method. The three test names are valid, empty and too long.

Java
public class MultipleInterfaces {

    interface Flyer {
        default String move() {
            return "fly";
        }
    }

    interface Swimmer {
        default String move() {
            return "swim";
        }
    }

    // Two defaults with the same signature: the class must choose
    static class Duck implements Flyer, Swimmer {
        @Override
        public String move() {
            return Flyer.super.move() + " and " + Swimmer.super.move();
        }
    }

    // A functional interface: exactly one abstract method, so a lambda can implement it
    @FunctionalInterface
    interface Validator {
        boolean isValid(String s);

        default Validator and(Validator other) {
            return s -> isValid(s) && other.isValid(s);
        }
    }

    public static void main(String[] args) {
        Duck d = new Duck();
        System.out.println("duck: " + d.move());
        System.out.println("duck is a Flyer: " + (d instanceof Flyer)
                + ", a Swimmer: " + (d instanceof Swimmer));

        Validator notEmpty = s -> !s.isEmpty();
        Validator shortEnough = s -> s.length() <= 8;
        Validator username = notEmpty.and(shortEnough);
        for (String name : new String[] {"ada", "", "averyverylongname"}) {
            System.out.println("[" + name + "] valid: " + username.isValid(name));
        }
    }
}

Output:

Output
duck: fly and swim
duck is a Flyer: true, a Swimmer: true
[ada] valid: true
[] valid: false
[averyverylongname] valid: false
  • Duck is both a Flyer and a Swimmer, and its move calls both defaults with X.super.move().
  • Validator has one abstract method, so a lambda can implement it. @FunctionalInterface makes the compiler check that it stays that way; default methods do not count.
  • The default and method returns a new validator that requires both, the same technique Predicate.and and Comparator.thenComparing use. See functional interfaces for the standard ones in java.util.function.

The rules javac enforces

The program compiles an interface that breaks four rules, plus a class that uses it wrongly, and prints javac's errors.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.tools.ToolProvider;

// Compiles an interface that breaks the rules and prints javac's errors
public class InterfaceRules {

    static final String SOURCE = """
            interface Account {
                int count = 0;                                   // a constant, not a field
                protected void audit();                          // 1: no protected members

                default boolean equals(Object o) { return true; } // 2: cannot default Object's

                static Account empty() { return null; }

                default void reset() { count = 1; }             // 3: count is final
            }

            class Savings implements Account {
                void use() {
                    Savings s = Savings.empty();                 // 4: statics not inherited
                }
            }
            """;

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("iface");
        Path file = dir.resolve("Account.java");
        Files.writeString(file, SOURCE);
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        ToolProvider.getSystemJavaCompiler().run(null, null,
                new PrintStream(err, true, StandardCharsets.UTF_8),
                "-d", dir.toString(), file.toString());
        err.toString(StandardCharsets.UTF_8).lines()
                .filter(l -> l.startsWith(file.toString()))
                .map(l -> l.substring(dir.toString().length() + 1))
                .forEach(System.out::println);
    }
}

Output:

Output
Account.java:3: error: modifier protected not allowed here
Account.java:5: error: default method equals in interface Account overrides a member of java.lang.Object
Account.java:9: error: cannot assign a value to static final variable count
Account.java:12: error: Savings is not abstract and does not override abstract method audit() in Account
Account.java:14: error: cannot find symbol
  • Line 3: interface members cannot be protected. Only public and, for methods with a body, private are allowed. (Constructors are not allowed either; that is a syntax error.)
  • Line 5: a default method cannot override equals, hashCode or toString. Every class already inherits these from Object, and by the "class wins" rule the default could never be used.
  • Line 9: count looks like a field but is a static final constant, so it cannot be assigned. Interfaces have no instance state.
  • Line 12: Savings did not implement the abstract audit, so it must either implement it or be abstract.
  • Line 14: static interface methods are not inherited. Savings.empty() is not found; it must be called as Account.empty(). This prevents conflicts when a class implements several interfaces with static methods of the same name.

Programming to interfaces, marker and sealed interfaces

The program writes a method that accepts any List and adapts to the implementation it receives by checking a marker interface, one with no methods at all. It then defines a sealed interface whose implementations are fixed, so a switch over it needs no default.

Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.RandomAccess;

public class ProgramToInterface {

    // Accepts any List: the caller chooses the implementation
    static int middle(List<Integer> list) {
        if (list instanceof RandomAccess) {          // a marker interface: no methods at all
            return list.get(list.size() / 2);
        }
        var it = list.listIterator(list.size() / 2);
        return it.next();
    }

    // A sealed interface (Java 17) with record implementations and an exhaustive switch
    sealed interface Payment permits Card, Transfer { }

    record Card(String last4, long cents) implements Payment { }

    record Transfer(String iban, long cents) implements Payment { }

    static String describe(Payment p) {
        return switch (p) {
            case Card c -> "card ending " + c.last4() + ", " + c.cents() + " cents";
            case Transfer t -> "transfer from " + t.iban() + ", " + t.cents() + " cents";
        };
    }

    public static void main(String[] args) {
        List<Integer> array = new ArrayList<>(List.of(10, 20, 30, 40, 50));
        List<Integer> linked = new LinkedList<>(array);
        System.out.println("middle of ArrayList:  " + middle(array)
                + " (RandomAccess: " + (array instanceof RandomAccess) + ")");
        System.out.println("middle of LinkedList: " + middle(linked)
                + " (RandomAccess: " + (linked instanceof RandomAccess) + ")");

        for (Payment p : List.of(new Card("4242", 1999), new Transfer("DE89...", 50000))) {
            System.out.println(describe(p));
        }
    }
}

Output:

Output
middle of ArrayList:  30 (RandomAccess: true)
middle of LinkedList: 30 (RandomAccess: false)
card ending 4242, 1999 cents
transfer from DE89..., 50000 cents
  • middle worked for both lists. RandomAccess declares nothing; ArrayList implements it to say "get(i) is fast", and LinkedList does not, so the method used a list iterator for it. JDK algorithms such as Collections.binarySearch check RandomAccess the same way. Serializable and Cloneable are other marker interfaces.
  • sealed interface Payment permits Card, Transfer allows exactly those two implementations. The compiler therefore knows the switch in describe covers every case; adding a third payment type would make it fail to compile until handled. See sealed classes.

Evolving an interface without breaking implementations

Once an interface is published, other code implements it, and that code is compiled separately. The program simulates a library and an application: version 1 of the library has a Shape interface with area, the application implements it, and then the library adds a perimeter method, first as an abstract method and then as a default method. Only the library is recompiled each time, as happens when an application upgrades a dependency JAR. The application calls perimeter through reflection so that the same compiled application can run against every version.

Java
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.spi.ToolProvider;

// Simulates a library adding a method to an interface that an application implements
public class EvolvingInterfaces {

    static void javac(Path dir, String... files) {
        String[] args = new String[files.length + 2];
        args[0] = "-d";
        args[1] = dir.toString();
        for (int i = 0; i < files.length; i++) {
            args[i + 2] = dir.resolve(files[i]).toString();
        }
        StringWriter out = new StringWriter();
        ToolProvider.findFirst("javac").orElseThrow()
                .run(new PrintWriter(out), new PrintWriter(out), args);
    }

    static String run(Path dir) throws Exception {
        try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()}, null)) {
            return (String) loader.loadClass("App").getMethod("run").invoke(null);
        } catch (InvocationTargetException e) {
            return e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage();
        }
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("evolve");
        Files.writeString(dir.resolve("Shape.java"),
                "public interface Shape { double area(); }");
        Files.writeString(dir.resolve("App.java"), """
                public class App {
                    static class Square implements Shape {
                        public double area() { return 4; }
                    }
                    public static String run() {
                        Shape s = new Square();
                        String r = "area " + s.area();
                        try {
                            Object p = Shape.class.getMethod("perimeter").invoke(s);
                            r += ", perimeter " + p;
                        } catch (ReflectiveOperationException e) {
                            Throwable c = e.getCause() == null ? e : e.getCause();
                            r += ", perimeter: " + c.getClass().getSimpleName();
                        }
                        return r;
                    }
                }
                """);
        javac(dir, "Shape.java", "App.java");
        System.out.println("version 1:                 " + run(dir));

        // The library adds an ABSTRACT method; the application is not recompiled
        Files.writeString(dir.resolve("Shape.java"),
                "public interface Shape { double area(); double perimeter(); }");
        javac(dir, "Shape.java");
        System.out.println("v2, abstract perimeter():  " + run(dir));

        // The library adds a DEFAULT method instead
        Files.writeString(dir.resolve("Shape.java"), """
                public interface Shape {
                    double area();
                    default double perimeter() { return Double.NaN; }
                }
                """);
        javac(dir, "Shape.java");
        System.out.println("v2, default perimeter():   " + run(dir));
    }
}

Output:

Output
version 1:                 area 4.0, perimeter: NoSuchMethodException
v2, abstract perimeter():  area 4.0, perimeter: AbstractMethodError
v2, default perimeter():   area 4.0, perimeter NaN
  • With version 1, perimeter does not exist, so the lookup fails with NoSuchMethodException, as expected.
  • When version 2 added an abstract perimeter(), the old Square class still loaded and area still worked, but calling perimeter threw AbstractMethodError: the interface promised a method the class never implemented. Recompiling the application would turn this into a compile error instead. Either way, every implementation must change.
  • With a default method, the old Square inherited the default and the call returned NaN. No implementation had to change. This is exactly how Java 8 added methods such as Collection.removeIf without breaking existing collection classes.
  • Default methods are not entirely risk-free: a class that already has a method with the same signature wins over the new default, even if its meaning is different, and a class implementing two interfaces that both add the same default stops compiling. When designing an interface for others to implement, keep it small and think about future methods early.

Interface or abstract class?

Choosing between an interface and an abstract class
NeedInterfaceAbstract class
A type that unrelated classes, records and enums can implementYesNo
Several types per classYes, any numberNo, one superclass
Shared codeDefault methods, without stateAny methods, with state
Instance fields and constructorsNoYes
Protected members for subclassesNoYes
Adding methods later without breaking implementersWith default methodsWith concrete methods

A common design uses both: an interface as the public type, and an abstract class that implements part of it for convenience, like List and AbstractList. Declare variables, parameters and return types with the interface (List, Map), and name the implementation only where the object is created.