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 Abstract, default, static and private methods Why default methods were added Multiple interfaces and functional interfaces The rules javac enforces Programming to interfaces, marker and sealed interfaces Evolving an interface without breaking implementations Interface or abstract class?
What an interface is
An interface is a contract: a list of methods that implementing types promise to provide. ListgetaddsizeArrayListLinkedListList
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 StringCharSequenceComparable<String>Serializable
| Member | Since | Notes |
|---|---|---|
| Abstract methods | 1.0 | Implicitly public abstract |
| Constants | 1.0 | Every field is implicitly public static final |
| Nested types | 1.1 | Implicitly public static |
default | 8 | Instance methods with a body that implementations inherit |
static | 8 | Called through the interface name only |
private | 9 | Helpers shared by default and static methods |
sealedpermits | 17 | Restricts which types may implement the interface |
What an interface still cannot have: instance fields, constructors, and protected
Abstract, default, static and private methods
The program defines a Shapearea
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:
Circle with area 3.14
Square(2.0) with area 4.00
Circle with area 7.07
largest: Circle
constant: 3.14
is written once, in the interface, and works for every shape because it calls the abstractdescribe , which each record implements. Onlyarea had to be written per type.area overrode the defaultSquare , so its line says "Square(2.0)"; the circles kept the default, which uses the class name.name is a static method: a helper that belongs with the type, called asShape.largest . Before Java 8 such helpers lived in separate utility classes, such asShape.largest(...) forCollections .Collection- The private
method keeps the default methods short without becoming part of the public contract.format 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.PI_APPROX
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 forEachremoveIfstreamCollectionIterableIterable.forEachCollection.removeIfList.sortMap.getOrDefault
The cost is that a class can now inherit code from several interfaces, so Java needs rules for conflicts. The program shows each rule.
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:
class wins: Base.name
more specific interface: Titled.name
conflict resolved: Labeled.name (chosen explicitly)
- The class wins.
inheritsChild fromname() and a defaultBase fromname() ; the class method was used. This keeps old classes working when a default with the same signature is added to an interface they implement.Named - The more specific interface wins.
extendsTitled and overrides its default, soNamed , which implements both, gotBook 's version.Titled - Otherwise the class must choose.
andNamed are unrelated, soLabeled would not compile without its ownProduct . Inside it,name() calls a specific interface's default.Labeled.super.name()
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.
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:
duck: fly and swim
duck is a Flyer: true, a Swimmer: true
[ada] valid: true
[] valid: false
[averyverylongname] valid: false
is both aDuck and aFlyer , and itsSwimmer calls both defaults withmove .X.super.move() has one abstract method, so a lambda can implement it.Validator makes the compiler check that it stays that way; default methods do not count.@FunctionalInterface- The default
method returns a new validator that requires both, the same techniqueand andPredicate.and use. SeeComparator.thenComparingfunctional 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.
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:
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
. Onlyprotected and, for methods with a body,public are allowed. (Constructors are not allowed either; that is a syntax error.)private - Line 5: a default method cannot override
,equals orhashCode . Every class already inherits these fromtoString , and by the "class wins" rule the default could never be used.Object - Line 9:
looks like a field but is acount constant, so it cannot be assigned. Interfaces have no instance state.static final - Line 12:
did not implement the abstractSavings , so it must either implement it or be abstract.audit - Line 14: static interface methods are not inherited.
is not found; it must be called asSavings.empty() . This prevents conflicts when a class implements several interfaces with static methods of the same name.Account.empty()
Programming to interfaces, marker and sealed interfaces
The program writes a method that accepts any Listswitchdefault
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:
middle of ArrayList: 30 (RandomAccess: true)
middle of LinkedList: 30 (RandomAccess: false)
card ending 4242, 1999 cents
transfer from DE89..., 50000 cents
worked for both lists.middle declares nothing;RandomAccess implements it to say "ArrayList is fast", andget(i) does not, so the method used a list iterator for it. JDK algorithms such asLinkedList checkCollections.binarySearch the same way.RandomAccess andSerializable are other marker interfaces.Cloneable allows exactly those two implementations. The compiler therefore knows the switch insealed interface Payment permits Card, Transfer covers every case; adding a third payment type would make it fail to compile until handled. Seedescribesealed 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 Shapeareaperimeterperimeter
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:
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,
does not exist, so the lookup fails withperimeter , as expected.NoSuchMethodException - When version 2 added an abstract
, the oldperimeter() class still loaded andSquare still worked, but callingarea threwperimeter : 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.AbstractMethodError - With a default method, the old
inherited the default and the call returnedSquare . No implementation had to change. This is exactly how Java 8 added methods such asNaN without breaking existing collection classes.Collection.removeIf - 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?
| Need | Interface | Abstract class |
|---|---|---|
| A type that unrelated classes, records and enums can implement | Yes | No |
| Several types per class | Yes, any number | No, one superclass |
| Shared code | Default methods, without state | Any methods, with state |
| Instance fields and constructors | No | Yes |
| Protected members for subclasses | No | Yes |
| Adding methods later without breaking implementers | With default methods | With 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 ListAbstractListListMap