Calling Superinterface Default Methods
You'll learn how to explicitly invoke a specific interface's default method when you need to choose between competing implementations.
The Syntax: InterfaceName.super.methodName()
When a class implements multiple interfaces with default methods, or when you override a default method but still want access to the original, Java provides special syntax to call a specific interface's default implementation:
InterfaceName.super.methodName()
This is similar to calling a superclass method with super.methodName(), but you must specify which interface you're referring to.
When You Need This
You've already seen that when multiple interfaces provide conflicting default methods, you must override the method to resolve the ambiguity. But what if you want to reuse one of those default implementations rather than writing everything from scratch?
interface Printer {
default void print() {
System.out.println("Printing from Printer");
}
}
interface Logger {
default void print() {
System.out.println("Logging from Logger");
}
}
class Reporter implements Printer, Logger {
@Override
public void print() {
// Explicitly call Printer's default implementation
Printer.super.print();
// Or call Logger's version
// Logger.super.print();
// Or both, or add custom behavior
System.out.println("Additional reporting logic");
}
}
Think of It as Delegation
Instead of reimplementing logic, you're delegating to a specific interface's version—like asking "the Printer version of you" to handle the task.
Key Takeaway: Use InterfaceName.super.methodName() to explicitly call a specific interface's default method implementation, essential for resolving conflicts or reusing interface behavior.