Using super to Call Specific Default Method
What you'll learn: How to explicitly invoke a particular interface's default method when your class implements multiple interfaces with conflicting defaults.
When your class implements multiple interfaces that provide default methods with the same signature, you've already seen that the compiler requires you to override the method to resolve the conflict. But what if you actually want to use one of those default implementations instead of writing your own from scratch?
Java provides special syntax for this: InterfaceName.super.methodName().
The Syntax
Inside your overriding method, you can call a specific interface's default implementation like this:
interface Flying {
default void move() {
System.out.println("Flying through the air");
}
}
interface Swimming {
default void move() {
System.out.println("Swimming through water");
}
}
class Duck implements Flying, Swimming {
@Override
public void move() {
// Call Flying's version specifically
Flying.super.move();
}
}
When you create a Duck and call move(), it prints "Flying through the air" because you explicitly chose Flying's default implementation.
Why This Matters
This syntax lets you:
- Reuse existing logic from one interface without rewriting it
- Delegate to a preferred default while adding your own behavior
- Combine multiple defaults: you could call both
Flying.super.move()andSwimming.super.move()in sequence
Think of it like having two instruction manuals for the same task. This syntax lets you say "use the instructions from this specific manual."
Key Takeaway: Use InterfaceName.super.methodName() inside an overriding method to invoke a specific interface's default implementation when multiple interfaces provide conflicting defaults.