- Prerequisites
- 7.1 Interfaces · 6.1 Inheritance
- Covers
- Implementing multiple interfaces · Default-method conflicts · Interface inheritance
- Related
- 7.4 Interface-Based Design · B1V2 Collections Framework · Book 5 Vol II (Interface Segregation)
On this page
1Concept / Definition
A Java class can extend only one class but can implement any number of interfaces, and an interface can extend any number of other interfaces. This is multiple inheritance of type (and, through default methods, of behaviour), without multiple inheritance of state. A class thereby takes on several roles at once.

2Why It Exists
Single class inheritance keeps objects simple: every object has exactly one chain of superclasses, so there is never a question of which parent's fields exist or which constructor runs first. Real types, however, play several roles at once. An invoice is sorted in reports, closed at month end and written to an audit log; a buffer is read by one component and written by another. Multiple interface inheritance lets a class declare all its roles without inheriting any state, and lets each client depend only on the role it uses.
It also lets contracts be built from smaller contracts. A List is a Collection, which is an Iterable, so code written for Iterable works with every list and set. Since Java 8 the same mechanism carries behaviour through default methods, which is why the language needs exact rules for the case where two roles bring the same method (section 3).
3Core Concepts
Implementing multiple interfaces
class Invoice implements Comparable<Invoice>, AutoCloseable, Auditable means an Invoice can be sorted, used in try-with-resources and audited — three unrelated capabilities. Each client sees only the role it needs: a sorting utility sees a Comparable, not an Invoice. This is the practical form of the Interface Segregation Principle: many small role interfaces rather than one large one.
Default-method conflicts
Because interfaces can carry default methods, two interfaces may provide the same method. If neither is more specific and the class does not override, compilation fails. The class resolves the conflict by overriding the method, and can call a particular interface's version with InterfaceName.super.method().

There is no ambiguity about state: interfaces have none, so the "diamond" in Java concerns only which method body to use, and the rules in 7.1 — class wins, most specific interface wins, otherwise override — always give a definite answer or a compile error.
Interface inheritance
An interface can extend several interfaces, inheriting all their abstract and default methods. The collections framework is the reference example: List, Set and Queue extend Collection, which extends Iterable. A sub-interface can refine the contract (a Set forbids duplicates) and override defaults of its parents.

4How It Works Internally
A class file lists its direct superinterfaces in its interfaces table: Invoice implements Comparable, AutoCloseable, Auditable stores three entries and no copy of any interface's code. Checks such as instanceof Auditable and casts to an interface search the set of all superinterfaces, and HotSpot keeps a per-class lookup structure that makes repeated checks cheap.
The JVM applies the resolution rules when a call is linked. A method declared in the class or a superclass is chosen first. Otherwise the JVM collects the maximally specific defaults from all superinterfaces; a default that a sub-interface overrides no longer counts. One candidate is selected; several candidates make the call fail with an IncompatibleClassChangeError (HotSpot throws its subclass AbstractMethodError). javac applies the same rules at compile time, so a conflict normally shows up as a compile error, and at run time only when interfaces changed after the class was compiled (Example 4). Flyer.super.move() compiles to invokespecial on the interface method, which is allowed only for a direct superinterface: a class cannot skip a level and call a grandparent's default.

5APIs / Features / Syntax
The syntax for combining roles is small. The table lists every form; the program after it uses intersection types, which let a single parameter or lambda carry two roles at once.
| Form | Meaning |
|---|---|
| class C extends B implements I, J | One superclass, any number of interfaces; extends comes first |
| interface K extends I, J | An interface extends any number of interfaces, never a class |
| I.super.m() | Calls the default of I; only where I is a direct superinterface of the caller |
| <T extends CharSequence & Closeable> | Intersection bound: T must have every listed type; a class, if any, comes first |
| (Supplier<String> & Serializable) () -> "ok" | Intersection cast: the lambda implements both; the extra types may have no abstract methods |
| x instanceof Auditable a | Asks whether an object plays a role, and binds it with that type |
import java.io.Closeable;
import java.io.Serializable;
import java.util.function.Supplier;
public class Intersections {
// T must play both roles: readable as a CharSequence and closeable
static <T extends CharSequence & Closeable> int lengthThenClose(T source)
throws java.io.IOException {
try (source) {
return source.length();
}
}
static final class Buffer implements CharSequence, Closeable {
private final String s; Buffer(String s) { this.s = s; }
public int length() { return s.length(); }
public char charAt(int i) { return s.charAt(i); }
public CharSequence subSequence(int a, int b) {
return s.subSequence(a, b);
}
public void close() { System.out.println("closed"); }
}
public static void main(String[] args) throws Exception {
System.out.println(lengthThenClose(new Buffer("ledger")));
// an intersection cast gives a lambda a second, marker interface
Supplier<String> s = (Supplier<String> & Serializable) () -> "ok";
System.out.println(s instanceof Serializable);
}
}closed
6
truelengthThenClose accepts only objects that are both a CharSequence and Closeable, so it can measure the text and close it without a cast; Buffer qualifies because it implements both. The intersection cast makes the lambda's generated class implement Serializable as well as Supplier, which is how a lambda is made serialisable (8.4 explains why that is rarely a good idea).
6Practical Examples
Example 1 — Resolving a conflict and combining roles
Problem. Two typical uses in one listing: a class that inherits the same default from two roles and must resolve it, and an interface that combines two roles so that one class offers both while each client asks for only one.
interface Flyer { default String move() { return "fly"; } }
interface Swimmer { default String move() { return "swim"; } }
class Duck implements Flyer, Swimmer {
@Override
public String move() { // required: conflict
return Flyer.super.move() + " and " + Swimmer.super.move();
}
}
interface Readable { String read(); }
interface Writable { void write(String s); }
// interface multiple inheritance
interface ReadWrite extends Readable, Writable {}
class MemoryBuffer implements ReadWrite {
private final StringBuilder sb = new StringBuilder();
public String read() { return sb.toString(); }
public void write(String s) { sb.append(s); }
}
void report(Readable source) { … } // needs only the read role
report(new MemoryBuffer());Why it works. Duck must override move, because neither Flyer nor Swimmer is more specific; inside the override, Flyer.super.move() and Swimmer.super.move() call each parent's default explicitly. MemoryBuffer implements ReadWrite and is therefore both a Readable and a Writable; report receives it as a Readable and cannot call write.
Example 2 — Mini program: one invoice, three roles, three clients
Problem. Figure 1 shows an invoice with three independent roles. This program builds it, together with three clients that each declare only the role they need: a generic largest method that needs ordering, a closeAll helper that needs AutoCloseable, and an audit method that needs Auditable.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Invoices {
interface Auditable { String auditLine(); }
static final class Invoice
implements Comparable<Invoice>, AutoCloseable, Auditable {
private final String id;
private final long amount;
private boolean open = true;
Invoice(String id, long amount) {
this.id = id;
this.amount = amount;
}
@Override public int compareTo(Invoice o) { // role 1: ordering
return Long.compare(amount, o.amount);
}
@Override public void close() { // role 2: a resource
open = false;
System.out.println(" closed " + id);
}
@Override public String auditLine() { // role 3: auditing
return id + " amount=" + amount + " open=" + open;
}
@Override public String toString() { return id; }
}
// each client asks only for the role it uses
static <T extends Comparable<T>> T largest(List<T> items) {
return Collections.max(items);
}
static void audit(List<? extends Auditable> items) {
items.forEach(a -> System.out.println(" " + a.auditLine()));
}
static void closeAll(List<? extends AutoCloseable> items)
throws Exception {
for (AutoCloseable c : items) c.close();
}
public static void main(String[] args) throws Exception {
List<Invoice> invoices = List.of(new Invoice("INV-1", 4_500),
new Invoice("INV-2", 12_000), new Invoice("INV-3", 800));
System.out.println("largest: " + largest(invoices));
List<Invoice> sorted = new ArrayList<>(invoices);
Collections.sort(sorted);
System.out.println("sorted: " + sorted);
System.out.println("month end:");
closeAll(invoices.subList(0, 2));
audit(invoices);
}
}largest: INV-2
sorted: [INV-3, INV-1, INV-2]
month end:
closed INV-1
closed INV-2
INV-1 amount=4500 open=false
INV-2 amount=12000 open=false
INV-3 amount=800 open=trueWhy it behaves this way. The same Invoice objects go to all three clients, but each parameter type limits what the client can do: largest can only compare, closeAll can only close, audit can only read the audit line. Collections.sort uses the same compareTo and orders by amount: 800, 4500, 12000. The roles are independent: after closeAll, the first two invoices report open=false while sorting and auditing still work. If the audit format changes, only Auditable and its implementations change; the sorting and month-end code are untouched, which is the Interface Segregation Principle at work.
Example 3 — Which default runs in a diamond
Problem. Section 3 states the resolution rules. This program builds a diamond with all four outcomes: a sub-interface that overrides the default, one that only inherits it, one that re-declares the method abstract, and a superclass that has the method.
public class Diamond {
interface Named { default String name() { return "Named"; } }
interface Product extends Named {
@Override default String name() { return "Product"; } // overrides
}
interface Taxable extends Named { } // inherits
interface Secret extends Named {
@Override String name(); // re-abstracts
}
static class Book implements Product, Taxable { } // diamond
static class Gift implements Taxable { }
static class Voucher implements Secret {
public String name() { return "Voucher"; } // must implement
}
static class Base { public String name() { return "Base"; } }
static class Sale extends Base implements Product { } // class wins
public static void main(String[] args) {
Taxable asTaxable = new Book();
System.out.println("Book " + new Book().name());
System.out.println("Gift " + new Gift().name());
System.out.println("Voucher " + new Voucher().name());
System.out.println("Sale " + new Sale().name());
System.out.println("Book seen as Taxable " + asTaxable.name());
}
}Book Product
Gift Named
Voucher Voucher
Sale Base
Book seen as Taxable ProductWhy it behaves this way. Book reaches name() through Product and through Taxable, but Taxable only inherits Named's default while Product overrides it, so Product is more specific and wins; there is no conflict to resolve. Gift sees only the inherited default. Secret re-declares name() abstract, which removes the default for its implementers, so Voucher must implement it. Sale inherits name() from Base, and a class method beats every default. The type of the variable does not matter: a Book seen as a Taxable still runs Product's code (Figure 4).
Example 4 — A conflict that appears only at run time
Problem. A conflict between defaults is normally a compile error. It appears at run time instead when two libraries each add the same default method in a new version and a class that implements both is not recompiled. This program builds that situation with the compiler API.
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.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
public class ConflictAtRunTime {
static final String WIDGET = "public class Widget"
+ " implements Audited, Cached {"
+ " public String tag() { return \"w\"; }"
+ " public int ttl() { return 60; } }";
public static void main(String[] args) throws Exception {
Path app = Files.createTempDirectory("app");
Path libs = Files.createTempDirectory("v2");
// version 1 of two libraries, and our class that implements both
compile(app, "public interface Audited { String tag(); }");
compile(app, "public interface Cached { int ttl(); }");
compile(app, WIDGET);
// version 2 of both libraries adds the same default method
compile(libs, "public interface Audited { String tag();"
+ " default String id() { return \"audit-\" + tag(); } }");
compile(libs, "public interface Cached { int ttl();"
+ " default String id() { return \"cache-\" + ttl(); } }");
compile(libs, "public class Caller { public static String run() {"
+ " Audited a = new Widget(); return a.id(); } }", app);
URL[] path = { libs.toUri().toURL(), app.toUri().toURL() };
try (var loader = new URLClassLoader(path, null)) {
loader.loadClass("Caller").getMethod("run").invoke(null);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
boolean icce = t instanceof IncompatibleClassChangeError;
String name = t.getClass().getSimpleName();
System.out.println("old Widget.class: " + name
+ ", an ICCE: " + icce);
}
// recompiling Widget against version 2 turns it into a compile error
Path again = Files.createTempDirectory("again");
System.out.println("recompiled Widget: "
+ compile(again, WIDGET, libs));
}
// compiles one public type; returns "ok" or the first error code
static String compile(Path dir, String source, Path... classPath)
throws Exception {
String name = source.split("\\s+")[2];
Path file = Files.writeString(dir.resolve(name + ".java"), source);
String cp = dir.toString();
for (Path p : classPath) cp += java.io.File.pathSeparator + p;
var javac = ToolProvider.getSystemJavaCompiler();
var diags = new DiagnosticCollector<JavaFileObject>();
try (var fm = javac.getStandardFileManager(diags, null, null)) {
List<String> options = List.of("-d", dir.toString(), "-cp", cp);
boolean ok = javac.getTask(null, fm, diags, options, null,
fm.getJavaFileObjects(file)).call();
return ok ? "ok" : diags.getDiagnostics().get(0).getCode();
}
}
}old Widget.class: AbstractMethodError, an ICCE: true
recompiled Widget: compiler.err.types.incompatibleWhy it behaves this way. When Widget was compiled, neither interface had id(), so javac had nothing to check. With version 2 on the class path, the call a.id() finds two maximally specific defaults and no method in Widget, and the JVM refuses to choose: HotSpot reports AbstractMethodError, a subclass of the IncompatibleClassChangeError that the JVM specification requires. Recompiling Widget against version 2 turns the same situation into the compile error types.incompatible. The fix is an override in Widget that chooses, for example return Audited.super.id();.
Example 5 — Conflicts that no override can resolve
Problem. Some combinations of roles cannot be fixed by an override, because the conflict is in the signatures, not in the bodies. The compiler rejects both classes below.
interface Counted { int size(); }
interface Measured { long size(); }
class Shelf implements Counted, Measured { // error 1
public int size() { return 3; }
}
record Price(long paise) { }
record Weight(long grams) { }
class Parcel implements Comparable<Price>, Comparable<Weight> { // error 2
public int compareTo(Price p) { return 0; }
}Why it behaves this way. int size() and long size() have the same name and parameters, so a class can declare only one size(), and either return type breaks the other contract: javac reports size() in Shelf cannot implement size() in Measured because return type int is not compatible with long. Comparable<Price> and Comparable<Weight> erase to the same interface, so Parcel can implement it only once: javac reports repeated interface and Comparable cannot be inherited with different arguments. The way out is composition: give Parcel two Comparator constants instead of two natural orders, and serve one of the size contracts through an adapter object (7.3).
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Combining interfaces whose contracts conflict (one requires mutability, another promises immutability) | The compiler cannot detect it; code that relies on one contract breaks the other, and the bug shows as wrong data, not as an error | Read the documented contracts before combining roles; if they conflict, use two objects (7.3) |
| Large "union" interfaces that extend many others | Clients depend on more than they use and must be rebuilt and retested whenever any part changes | Let clients ask for the small role interfaces; keep the union for implementers |
| Significant behaviour in default methods of several interfaces | Which body runs depends on the resolution rules, and a library upgrade can change the answer (Example 4) | Keep defaults small; in a class that combines roles, override and choose with X.super.m() |
| Calling a grandparent's default with X.super.m() | Does not compile: X.super works only for a direct superinterface | Call the direct superinterface's method, or move shared code into a static helper |
| Implementing one generic interface twice, e.g. Comparable<Price> and Comparable<Weight> | Does not compile: both erase to one interface (Example 5) | Offer Comparator constants for the extra orders |
| Checking roles with instanceof on concrete classes | The check misses every new class that takes on the role | Test for the role interface, or better, declare the role as the parameter type |
8Performance & Production Considerations
- Implementing several interfaces costs nothing per object: interfaces add no fields, so an object's size depends only on its class's fields. Each interface adds a few entries to the class's method tables.
- A call through a role interface that many classes implement can become megamorphic: the JIT cannot inline it and uses an itable search instead. It rarely matters, but in a hot loop over mixed types a profiler shows it as time in itable stubs.
- A library upgrade can introduce a default-method conflict without any change to your code (Example 4). Run the tests against exactly the library versions that ship, and treat a new default in a widely implemented interface as a change that needs a compatibility check.
- Role interfaces make access easier to audit: a component that receives only a read role cannot write, which a code review or an architecture test can verify.
9Architecture & Design Considerations
Multiple interface inheritance supports role-based design: a component exposes different interfaces to different clients — an admin view and a customer view of the same service, a read port and a write port (as in CQRS). Clients depend only on the role they need, which keeps coupling low and allows roles to be split into separate components later.
10Interview Questions & Answers
Can a Java class implement multiple interfaces? Can it extend multiple classes?
It can implement any number of interfaces but extend only one class. A declaration such as class Invoice extends Document implements Comparable<Invoice>, AutoCloseable is legal; extends Document, Audit is not, because two superclasses could each bring fields and constructors.
What happens when a class implements two interfaces with the same default method?
Compilation fails unless the class overrides the method. In the override it can call a particular default with InterfaceName.super.method(), or provide new behaviour.
Why does multiple interface inheritance not cause the diamond problem that multiple class inheritance would?
Interfaces have no instance state, so there is never ambiguity about which fields exist. The only possible ambiguity is between method bodies, and Java resolves it with fixed rules or a compile error that forces the class to decide.
Can an interface extend multiple interfaces?
Yes. It inherits all their methods, and can add new ones, refine contracts, and override inherited defaults. For example, List extends SequencedCollection (Java 21), which extends Collection. If two parents bring conflicting defaults, the sub-interface must override the method, just as a class must.
How does interface segregation relate to multiple interface inheritance?
Instead of one broad interface, define small role interfaces and let classes implement several. Each client depends only on the role it uses, so changes to other roles do not affect it — the Interface Segregation Principle.
How can role interfaces support later architectural changes such as CQRS or splitting a service?
If clients already depend on separate read and write interfaces, the implementations behind them can later be separated into different components or services without changing clients. Role interfaces make such splits a wiring change rather than a rewrite.
In a class declaration, which comes first, extends or implements? Can an interface extend a class?
extends comes first: class Duck extends Bird implements Flyer, Swimmer. An interface can extend any number of interfaces with extends, but never a class, and it cannot use implements at all.
What does this program print?
public class DiamondQuiz {
interface A { default String hi() { return "A"; } }
interface B extends A {
default String hi() { return "B" + A.super.hi(); }
}
interface C extends A { }
static class D implements B, C { }
static class E implements C {
public String hi() { return "E" + C.super.hi(); }
}
public static void main(String[] args) {
A d = new D();
System.out.println(new D().hi() + " " + new E().hi() + " "
+ d.hi());
}
}It prints BA EA BA. D gets hi() through B and through C; C only inherits A's default, so B, which overrides it, is more specific and wins, and B's body calls A.super.hi() (legal, because A is a direct superinterface of B). E implements only C and may call C.super.hi(), which runs the default C inherited from A. The cast to A changes nothing: the method is selected from the object's class.
Interfaces Counted { int size(); } and Measured { long size(); }: can one class implement both? And Comparable<Price> together with Comparable<Weight>?
Neither compiles (Example 5). The two size() methods have the same signature but incompatible return types, and a class can declare only one size(). The two Comparables erase to the same interface, so the class would implement it twice. An override cannot fix either case; use a separate object or adapter for one role, and Comparator constants for extra orderings.
Why may Duck call Flyer.super.move(), while a class that implements only B, where B extends A, may not call A.super.hi()?
X.super.m() compiles to invokespecial, which the language and the JVM allow only for a direct superinterface of the calling class, so that a class cannot bypass an override in an interface it does implement. Flyer is listed in Duck's implements clause; A is not listed in the second class. It can call B.super.hi(), which runs B's version, and B itself may call A.super.hi().
After two libraries are upgraded, a class that implements interfaces from both fails in production with AbstractMethodError on id(), although every test passed. How do you diagnose and fix it?
Both new versions added a default id(), and the class was compiled against the old ones, so the JVM finds two candidates and refuses to choose (Example 4). The tests passed because they ran against other versions than the deployed artefact, for example a plug-in built earlier or a different resolved dependency set. Check the shipped versions with the dependency tree and javap on the deployed JARs, recompile the class against them, which turns the problem into a compile error, and override id() to choose. Then make the tests run against the exact artefact that ships.
How would you let a customer app and a back-office tool use the same order component with different permissions?
Define two role interfaces, for example CustomerOrders (place, view own orders) and OrderAdmin (refund, cancel any order), and let one class implement both. Inject only the narrow role into each client, so the customer-facing code cannot even call refund. Security checks still belong at the boundary, but the type system now documents and enforces who may do what, and the two roles can later be split into separate components without changing their clients.
One broad interface or several role interfaces for a component that five teams use: which do you choose, and what does each cost?
Role interfaces, cut along how the teams actually use the component. They cost more types and a little more wiring, and a poorly chosen split forces clients to depend on several roles anyway. In return, each team depends only on what it calls, changes to one role do not force the others to rebuild, and test doubles are smaller. A broad interface is acceptable while there is one client and the shape is still changing; split it when the second team arrives.
A widely implemented public interface needs a new capability. Do you add a default method or publish a new sub-interface such as PaymentV2 extends Payment? Defend the choice.
A default is the least disruptive when a sensible implementation exists in terms of the existing methods and the name cannot clash: every implementer gets it for free. A sub-interface is better when there is no safe default, when implementers must make a conscious decision, or when the name could collide with methods partners already have (Figure 7 of 7.1, Example 4). Its cost is that callers must check instanceof PaymentV2, so publish a clear support policy and a deprecation path for the old interface.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- One superclass, many interfaces: multiple inheritance of type, not of state.
- Default conflicts must be resolved by overriding; X.super.m() picks a parent default.
- Interfaces can extend multiple interfaces to build hierarchies of contracts.
- Small role interfaces keep clients' dependencies minimal.