Tuesday, 12 January 2016

Java Tutorial : Java Interface (Duplicate default methods-Super)

Master Core Java Step-by-Step!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!

Subscribe Now on YouTube

Resolving Duplicate Default Methods with InterfaceName.super

When a Java class implements multiple interfaces that contain identical default method signatures, the compiler triggers an ambiguity error. Rather than writing completely new implementation logic from scratch, what if you want to reuse the exact behavior already provided by one of those interfaces?

Java provides a targeted syntax to accomplish this: InterfaceName.super.methodName();. This allows you to resolve the conflict explicitly while delegating execution to the specific interface implementation you want.

Why Not Just Use super.methodName()?

In standard class inheritance, calling super.methodName() works because a class can only extend one parent. However, in multiple interface inheritance:

  • Multiple Super-types: A class can implement multiple interfaces, so a plain super call would remain ambiguous to the compiler.
  • Explicit Qualification: Prefacing super with the interface name (e.g., Vehicle.super.start()) makes your exact choice crystal clear to the compiler.
  • Clean Code Reuse: You avoid copy-pasting logic from an interface's default body into your class.

Code Example: Explicit Delegation Using InterfaceName.super

interface Printer {
  default void show() {
    System.out.println("Displaying from Printer interface");
  }
}

interface Scanner {
  default void show() {
    System.out.println("Displaying from Scanner interface");
  }
}

class MultiFunctionMachine implements Printer, Scanner {
  @Override
  public void show() {
    // Explicitly invoke Printer's default method
    Printer.super.show();
  }
}

public class Test {
  public static void main(String[] args) {
    MultiFunctionMachine machine = new MultiFunctionMachine();
    machine.show();
  }
}

Output:

Displaying from Printer interface

Key Takeaways

  1. Whenever identical default methods collide, the implementing class must override the method.
  2. Use InterfaceName.super.methodName() to reuse one or even both interface implementations inside the overridden method.
  3. This pattern completely resolves compile-time ambiguity while maximizing code reuse across interface contracts.

Watch More Java Interface Tutorials:

No comments:

Post a Comment

Tutorials