Default Method Conflict Resolved Explicitly
When two interfaces supply the same default method, the implementing class must override it and pick a side with InterfaceName.super.method().
Code
interface CacheBackend {
default String describe() {
return "cache backend";
}
}
interface MetricsBackend {
default String describe() {
return "metrics backend";
}
}
// implementing both interfaces inherits two same-named default methods, so the conflict must be settled explicitly
final class Telemetry implements CacheBackend, MetricsBackend {
@Override
public String describe() {
// InterfaceName.super.method() picks which side to keep; combining both is also common
return CacheBackend.super.describe() + " + " + MetricsBackend.super.describe();
}
}
public class InterfaceConflict {
public static void main(String[] args) {
System.out.println(new Telemetry().describe());
// implementing just one interface needs no settlement: the default method is inherited as-is
CacheBackend solo = new CacheBackend() {};
System.out.println(solo.describe());
}
}How the snippet works
Default Method Conflict Resolved Explicitly reduces to the classes CacheBackend, MetricsBackend, Telemetry and InterfaceConflict and the functions describe and main.
Applying it
The entry-point signature is public String describe()
main sequences describe; executing the file runs that flow once.
Statements that matter
return CacheBackend.super.describe() + " + " + MetricsBackend.super.describe();
return "metrics backend";
return "cache backend";
Interactive Tools for This Topic
FAQ
- How do you run Default Method Conflict Resolved Explicitly?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.