Suppose you have multiple interfaces with default methods that a class implements. How would you resolve method conflicts?

When a class implements multiple interfaces that contain default methods with the same method signature, Java cannot automatically decide which implementation should be used. To avoid ambiguity, the implementing class must override the conflicting method and provide its own implementation. Inside the overridden method, it can explicitly invoke a specific interface's default method using InterfaceName.super.methodName().

Key Points:

• Default method conflicts occur when multiple interfaces define the same default method signature. • The implementing class must override the conflicting method; otherwise, a compilation error occurs. • InterfaceName.super.methodName() allows calling a specific interface's default implementation. • The class can choose one interface implementation or create completely custom logic. • This feature supports multiple interface inheritance while preventing ambiguity.

Example:

Imagine two interfaces, Printer and Scanner, both provide a default print() method. A class implementing both interfaces must explicitly decide which print() implementation to use.

Code Example:

interface Printer {
    default void print() {
        System.out.println("Printer default method");
    }
}

interface Scanner {
    default void print() {
        System.out.println("Scanner default method");
    }
}

public class MultiFunctionDevice implements Printer, Scanner {

    @Override
    public void print() {
        Printer.super.print(); // Choosing Printer's implementation
    }

    public static void main(String[] args) {
        MultiFunctionDevice device = new MultiFunctionDevice();
        device.print();
    }
}

Interview Tip:

A concise interview answer is: "If multiple interfaces provide the same default method, the implementing class must override that method to resolve the conflict. It can then explicitly invoke a specific interface's implementation using InterfaceName.super.methodName() or provide its own custom implementation."