- Prerequisites
- 5.2 Abstraction · 6.3 Polymorphism
- Covers
- Interface declaration · Interface methods · Interface fields · Default methods · Static methods · Private interface methods
- Related
- 7.2 Multiple Interface Inheritance · 7.4 Interface-Based Design · 8.4 Relationship with Lambdas · B1V3 Functional Interfaces
On this page
1Concept / Definition
An interface is a reference type that declares a contract: a set of methods that implementing classes promise to provide. It has no instance state and no constructors. A class declares implements to take on the contract, and any number of unrelated classes can implement the same interface. A variable of an interface type can hold any implementing object.

Interfaces have grown from pure contracts into a richer construct. Since Java 8 they can carry default and static methods, since Java 9 private helper methods, and since Java 17 they can be sealed. The core idea remains: an interface describes what, classes decide how.

2Why It Exists
Interfaces give Java multiple inheritance of type without the problems of multiple inheritance of state. They let unrelated classes share a role — a Document, an Invoice and a ZipFile can all be AutoCloseable — and let client code depend on that role rather than on any class. They are also the targets of lambdas, the basis of the collections framework, and the foundation of dependency injection and plugin systems.
3Core Concepts
Interface declaration
An interface is declared with interface, optionally public, and may extend other interfaces with extends (7.2). It may be generic (interface Repository<T, ID>) and sealed (sealed interface Payment permits Card, Upi). Implementing classes use implements; an abstract class may implement an interface partially and leave the rest to subclasses.

Interface methods
Methods without a body are implicitly public abstract. Every concrete implementing class must provide them. The contract of each method — parameters, return value, exceptions, side effects — should be documented, because it is all that callers can rely on (5.2).
Interface fields
Any field declared in an interface is implicitly public static final: a constant. Interfaces cannot have instance fields. Constants in interfaces are occasionally useful, but a constant interface — an interface that exists only to hold constants, implemented by classes to use short names — is an anti-pattern: it makes implementation details part of the class's public type.

Default methods
A default method has a body and is inherited by implementing classes unless they override it. Default methods were introduced so that existing interfaces could evolve — Collection gained stream() and removeIf() without breaking every implementation in existence. They are also used to provide convenience methods built on the abstract ones, such as Comparator.reversed().
When several sources provide a method, Java resolves it with three rules:

Static methods
Static methods in interfaces belong to the interface and are called through its name: List.of(...), Comparator.comparing(...), Map.entry(...). They are not inherited by implementing classes. They are ideal for factory methods and utilities closely tied to the interface, replacing separate utility classes such as Collections.
Private interface methods
Since Java 9 an interface can declare private methods (instance or static) to share code between its default and static methods without exposing that code to implementers or callers.

4How It Works Internally
An interface compiles to a class file with the ACC_INTERFACE flag. Calls through an interface type use invokeinterface; HotSpot resolves them through interface method tables (itables) and, like virtual calls, inlines them when the call site sees one or two implementations. Default methods are real methods in the interface's class file; an implementing class that does not override them uses the interface's code. Lambdas implement functional interfaces by generating an implementation class at run time through invokedynamic (8.4).
shape.describe() compiles to invokeinterface Shape.describe. When the call is linked, the JVM looks for an implementation in the object's class and superclasses first and takes a default only if there is none: the "class wins" rule of Figure 5, enforced by the VM. Static interface methods are called with invokestatic on the interface and are not inherited, so Square.unitSquare() does not compile. Because selection happens at run time, an old class picks up a default added later, and some other changes to an interface fail only at run time (Example 4).
5APIs / Features / Syntax
public sealed interface Shape permits Circle, Square { // Java 17+
double area(); // abstract
default String describe() { // default
return name() + " with area " + format(area());
}
static Shape unitSquare() { return new Square(1); } // static factory
private String name() { return getClass().getSimpleName(); } // private
private static String format(double v) { return "%.2f".formatted(v); }
}
record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
}
record Square(double side) implements Shape {
public double area() { return side * side; }
}@FunctionalInterface
public interface PriceRule {
Money apply(Money price); // exactly one abstract method
default PriceRule andThen(PriceRule next) { // defaults don't count
return price -> next.apply(apply(price));
}
}
PriceRule tenOff = p -> p.percentOff(10);
PriceRule roundDown = Money::roundDown;
Money result = tenOff.andThen(roundDown).apply(price);6Practical Examples
Example 1 — Evolving a published interface safely
public interface NotificationSender {
void send(Notification n);
// Added in v2 — existing implementations keep compiling
default void sendAll(List<Notification> batch) {
batch.forEach(this::send);
}
}Why it works. A class compiled against version 1 has no sendAll; the JVM finds the default in the interface when it is first called, so existing senders need no change. A sender that can submit a batch in one request overrides it. Example 4 shows which other changes are safe.
Example 2 — Mini program: a discount engine built on one interface
Problem. Section 5 shows a functional interface with one default method. This program builds a small but complete discount engine on one interface and uses every member kind an interface can have: the abstract method that lambdas implement, a default method that chains rules, static factory methods that validate their arguments, and a private helper that the factories share without exposing it.
import java.util.List;
public class DiscountEngine {
record Money(long paise) {
Money minus(long p) { return new Money(Math.max(0, paise - p)); }
Money percentOff(int pct) {
return new Money(paise - paise * pct / 100);
}
@Override public String toString() {
return "Rs %d.%02d".formatted(paise / 100, paise % 100);
}
}
@FunctionalInterface
interface Discount {
Money apply(Money price); // the one abstract method
default Discount then(Discount next) { // default, built on apply
return price -> next.apply(apply(price));
}
static Discount percent(int pct) { // static factories
check(pct >= 0 && pct <= 100, "percent " + pct);
return price -> price.percentOff(pct);
}
static Discount flat(long rupees) {
check(rupees >= 0, "flat " + rupees);
return price -> price.minus(rupees * 100);
}
static Discount all(List<Discount> rules) {
return rules.stream().reduce(price -> price, Discount::then);
}
private static void check(boolean ok, String what) { // private
if (!ok) throw new IllegalArgumentException("invalid: " + what);
}
}
public static void main(String[] args) {
Money price = new Money(1_999_00);
Discount festive = Discount.percent(10).then(Discount.flat(100));
Discount loyalty = p -> p.paise() > 1_000_00 ? p.minus(50_00) : p;
System.out.println("list price " + price);
System.out.println("festive " + festive.apply(price));
System.out.println("festive+loyalty "
+ Discount.all(List.of(festive, loyalty)).apply(price));
try {
Discount.percent(120);
} catch (IllegalArgumentException e) {
System.out.println("rejected " + e.getMessage());
}
}
}list price Rs 1999.00
festive Rs 1699.10
festive+loyalty Rs 1649.10
rejected invalid: percent 120Why it behaves this way. The factories return lambdas, so callers see only the Discount type. then is a default built on the abstract apply, so any rule, including the caller's loyalty lambda, can be chained; all folds a list with reduce, starting from price -> price. Rs 1999.00 less 10% is Rs 1799.10, less Rs 100 it is Rs 1699.10, and loyalty takes Rs 50 more. The private check is shared by the factories but invisible to implementers and callers.
Example 3 — AutoCloseable as a role
public final class ReportWriter implements AutoCloseable {
private final BufferedWriter out;
public ReportWriter(Path file) throws IOException { out = Files.newBufferedWriter(file); }
public void line(String s) throws IOException { out.write(s); out.newLine(); }
@Override public void close() throws IOException { out.close(); }
}
// closed automatically
try (var writer = new ReportWriter(Path.of("report.csv"))) {
writer.line("id,total");
}Example 4 — What breaks when a published interface changes
Problem. Example 1 adds a method safely. Other changes to a published interface are not safe, and the danger is that they fail only at run time, in code nobody recompiled: a plug-in, or a library built against the older version. This program compiles version 1 of an interface and one implementation, then two different versions 2 of the interface and a caller, and runs the caller with the old implementation's class file.
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.tools.ToolProvider;
public class InterfaceEvolution {
static final String V1 =
"public interface Greeter { String greet(String n); }";
static final String IMPL = "public class Polite implements Greeter {"
+ " public String greet(String n) { return \"Hello, \" + n; } }";
static final String CALLER = "public class Caller {"
+ " public static String run() { Greeter g = new Polite();"
+ " return g.greet(\"Asha\") + \" / \""
+ " + g.farewell(\"Asha\"); } }";
public static void main(String[] args) throws Exception {
Path v1 = Files.createTempDirectory("v1");
compile(v1, "Greeter", V1, v1);
compile(v1, "Polite", IMPL, v1); // plug-in built once, against v1
System.out.println("v2 adds an abstract method: " + tryV2(v1,
"public interface Greeter { String greet(String n);"
+ " String farewell(String n); }"));
System.out.println("v2 adds a default method: " + tryV2(v1,
"public interface Greeter { String greet(String n);"
+ " default String farewell(String n) {"
+ " return \"Bye, \" + n; } }"));
}
// compile Greeter v2 and Caller, then run them with the OLD Polite.class
static String tryV2(Path v1, String greeterV2) throws Exception {
Path v2 = Files.createTempDirectory("v2");
compile(v2, "Greeter", greeterV2, v1);
compile(v2, "Caller", CALLER, v1);
URL[] path = { v2.toUri().toURL(), v1.toUri().toURL() }; // v2 first
try (var loader = new URLClassLoader(path, null)) {
return (String) loader.loadClass("Caller")
.getMethod("run").invoke(null);
} catch (InvocationTargetException e) {
return e.getCause().getClass().getSimpleName();
}
}
static void compile(Path dir, String name, String source, Path classPath)
throws Exception {
Path file = Files.writeString(dir.resolve(name + ".java"), source);
int rc = ToolProvider.getSystemJavaCompiler().run(null, null, null,
"-d", dir.toString(),
"-cp", dir + java.io.File.pathSeparator + classPath,
file.toString());
if (rc != 0) throw new IllegalStateException("javac failed: " + name);
}
}v2 adds an abstract method: AbstractMethodError
v2 adds a default method: Hello, Asha / Bye, AshaWhy it behaves this way. Polite.class contains no farewell. With an abstract farewell, recompiling Polite would fail, but nobody recompiles it: the JVM loads the old class, and the first call finds no implementation and throws AbstractMethodError. With a default, the JVM selects the interface's code and the call works. Figure 7 sums up the cases; 7.2 shows the last one.

Example 5 — Plug-ins found at run time with ServiceLoader
Problem. An interface is also the unit of extension: the application defines it, and providers that the application never names implement it. java.util.ServiceLoader finds the providers at run time, from a registration file or from provides clauses in module descriptors. priority was added later as a default, so older providers still load.
package com.example.codec;
public interface Codec { // the SPI: small and documented
String name();
String encode(String text);
default int priority() { return 0; } // added later, as a default
}package com.example.codec;
import java.util.Comparator;
import java.util.ServiceLoader;
public class Plugins {
public static final class Upper implements Codec { // provider 1
public String name() { return "upper"; }
public String encode(String t) { return t.toUpperCase(); }
}
public static final class Reverse implements Codec { // provider 2
public String name() { return "reverse"; }
public String encode(String t) {
return new StringBuilder(t).reverse().toString();
}
@Override public int priority() { return 10; }
}
public static void main(String[] args) {
ServiceLoader<Codec> loader = ServiceLoader.load(Codec.class);
for (Codec c : loader) {
System.out.println(c.name() + " -> " + c.encode("order-42"));
}
Codec best = loader.stream().map(ServiceLoader.Provider::get)
.max(Comparator.comparingInt(Codec::priority)).orElseThrow();
System.out.println("highest priority: " + best.name());
}
}com.example.codec.Plugins$Upper
com.example.codec.Plugins$Reverseupper -> ORDER-42
reverse -> 24-redro
highest priority: reverseWhy it behaves this way. The registration file is named after the interface and lists one provider per line. ServiceLoader creates each provider lazily with its public no-argument constructor, in file order. Upper inherits priority 0 from the default, so Reverse wins with 10. In a modular application the provider declares provides ... with and the consumer uses; registration files in named modules are ignored (Q14).
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Fat interfaces with many unrelated methods | Implementers must stub methods they don't need; the stubs throw UnsupportedOperationException, so a caller finds the gap only at run time | Split into focused interfaces (ISP, Book 5), each named for the role a client uses |
| Business logic in default methods | Logic hidden in the contract; hard to override consistently; implementers inherit behaviour they never see in their own code and cannot test on its own | Keep defaults to convenience built on abstract methods; put real logic in a class that users can see, test and replace |
| Constant interfaces | Constants become public API of implementers, and of all their subclasses, and cannot be removed without breaking them | enum or final constants class with a private constructor, used through import static |
| Changing abstract method signatures in published interfaces | Breaks every implementation: a compile error after recompiling, AbstractMethodError in class files built earlier (Example 4) | Add new methods as defaults; deprecate old ones, and check binary compatibility in the build |
| Interfaces mirroring one class's public methods | Indirection with no variation point; every change to the class changes the interface too, so nothing is decoupled | Design interfaces from the client's need, and add one only where a second implementation or a test double really exists |
| Expecting static interface methods to be inherited | Impl.of() does not compile, and helpers get copied into implementing classes | Call them through the interface name: List.of(...), Comparator.comparing(...) |
| A lambda target without @FunctionalInterface | Someone adds a second abstract method, and every lambda that implements the interface stops compiling | Annotate it, so the compiler rejects the second abstract method |
| A provider that is not registered | ServiceLoader finds nothing; the feature silently falls back or disappears | Register it in META-INF/services or with provides ... with, and test the lookup (Example 5) |
8Performance & Production Considerations
- Interface calls cost the same as virtual calls after JIT profiling and inlining; no need to avoid them. Only call sites that see many implementations (megamorphic sites) fall back to an itable search, which costs slightly more than a virtual call and matters only in the hottest loops.
- Adding a default method to an interface implemented by third parties can clash with methods they already have, with the same name but different semantics. Review default additions to widely implemented interfaces carefully.
- An interface that other teams implement is an API. Check binary compatibility in the build with an API-comparison tool, and treat a removed or changed abstract method as a breaking change that needs a new major version (Figure 7).
9Architecture & Design Considerations
Interfaces are the primary unit of architecture in object-oriented systems: they are the ports in hexagonal architecture, the SPIs of plugin systems, and the types that DI containers wire. The design rules scale: keep interfaces small and cohesive (Interface Segregation), design them from the consumer's point of view, document contracts, and evolve them additively with default methods and deprecation rather than breaking changes.
10Interview Questions & Answers
What can an interface contain in Java 25?
Abstract methods, default methods, static methods, private (instance and static) methods, constants (public static final fields) and nested types. It cannot have instance fields or constructors. It can also be sealed.
What is a functional interface?
An interface with exactly one abstract method, such as Runnable, Supplier or Function. It can be implemented by a lambda or method reference. @FunctionalInterface asks the compiler to enforce the single-abstract-method rule; default and static methods do not count.
Why were default methods added to Java?
To allow existing interfaces, especially in the collections framework, to gain new methods such as stream and forEach in Java 8 without breaking the many classes that already implemented them. Without them, adding stream() to Collection would have broken every collection class outside the JDK. The same technique lets any library add methods to a published interface (Example 1).
What is the difference between a static and a default method in an interface?
A default method is an instance method with a body that implementers inherit and may override; it can call other interface methods on this. A static method belongs to the interface itself, is called through the interface name, and is not inherited.
How are default method conflicts resolved?
A method in the class or its superclasses wins over any default. Otherwise the most specific interface's default wins. If two unrelated interfaces provide the same default, the class must override the method and may call a specific one with InterfaceName.super.method().
Why is the constant interface considered an anti-pattern?
Implementing an interface just to use its constants makes those constants part of the class's public type and API, pollutes subclasses, and cannot be undone without breaking compatibility. Use an enum, a final class of constants with a private constructor, or configuration.
What are the risks of adding a default method to a widely implemented interface?
Existing implementations may already have a method with the same signature but different meaning, which will silently override the default; or two interfaces may now provide conflicting defaults, breaking compilation of implementers. Review usage and document the default's contract carefully.
When would you use an abstract class instead of an interface in modern Java?
When implementations need shared instance state, constructors, or protected helper methods — typically as a convenience base class implementing an interface. The interface remains the type clients depend on. Since Java 8 an interface can carry shared behaviour as defaults, so the abstract class is needed only for state and constructors. A common pattern pairs them: an interface for clients and an optional skeleton such as AbstractList for implementers.
What makes a good interface for a module or service boundary?
Small and cohesive, named for the capability, designed from the consumer's needs, with documented contracts (inputs, outputs, errors, side effects), free of implementation types in its signatures, and evolvable additively. Provide contract tests implementations must pass.
How do sealed interfaces change domain modelling?
They define a closed, compiler-known set of variants, typically records. Code can switch over them exhaustively without a default, so adding a new variant produces compile errors exactly where handling is missing — a safer alternative to open hierarchies for stable business concepts.
How would you design the extension SPI for a platform that other teams build plugins for?
Publish a small, versioned interface in a separate API module with no implementation dependencies; document the contract and threading and error semantics; discover implementations via ServiceLoader or DI; add capabilities only through default methods or new optional interfaces; and provide a contract-test kit plugins must pass. Keep internal classes unexported so plugins can depend only on the SPI.
What does this program print?
public class InterfaceQuiz {
interface Greeter {
String NAME = "greeter"; // public static final
String name();
default String greet() { return "Hello from " + name(); }
static String id() { return "Greeter"; } // not inherited
}
static class Base { public String greet() { return "Base wins"; } }
static class A extends Base implements Greeter {
public String name() { return "A"; }
}
static class B implements Greeter {
public String name() { return "B"; }
}
public static void main(String[] args) {
Greeter a = new A(), b = new B();
System.out.println(a.greet());
System.out.println(b.greet());
System.out.println(Greeter.id() + " " + B.NAME);
}
}It prints Base wins, Hello from B, Greeter greeter. A inherits greet() from Base, and a class method always beats a default. B inherits the default, which calls name() on this. Greeter.id() must be called through the interface, because static interface methods are not inherited (B.id() would not compile), while the constant NAME is inherited and can be named through B.
A plug-in compiled against version 1 of an interface keeps working after the host moves to version 2, until one call fails with AbstractMethodError. What happened, and how could the host have avoided it?
Version 2 added an abstract method. The JVM does not check at load time that a class implements every abstract method of its interfaces, so the old plug-in loaded and worked until the first call of the new method found no implementation (Example 4). A default method would have given old plug-ins an implementation; the host can also refuse, at startup, plug-ins built against an older API version.
After a service moves to the module system (module-info.java), the startup log shows that ServiceLoader found no payment providers and payments silently use a fallback. What is wrong, and how do you fix and guard against it?
In named modules, META-INF/services files are ignored: the provider module must declare provides PaymentProvider with CardProvider; and the consumer module must declare uses PaymentProvider;, otherwise ServiceLoader.load fails with ServiceConfigurationError. Here the lookup worked but no provider was declared. Add the provides clauses, fail at startup when a required provider is missing instead of falling back, and add a test on the module path that checks the provider list.
For a public SDK that partners implement, would you expose interfaces with default methods or abstract base classes, and how would you plan its evolution?
Interfaces, with an optional abstract skeleton for convenience. Interfaces leave partners free to extend their own classes and work with lambdas, proxies and records; an abstract class ties every partner to your hierarchy. Plan evolution from the start: version the API module, add capabilities only as defaults or new optional interfaces detected with instanceof, never change an abstract method in a minor release, and publish contract tests that partners run before you release.
Test your knowledge on this topic →Flashcards from this topic's 15 questions, filtered by level and type.
Key Takeaways
- An interface is a contract and a type; no instance state, no constructors.
- Members: abstract, default, static, private methods and constants; interfaces can be sealed.
- Default-method resolution: class wins, then most specific interface, else override.
- Functional interfaces are the targets of lambdas.
- Small, consumer-focused interfaces are the building blocks of loosely coupled architecture.