Can we have a default method in an Interface? If yes, then why is it required?

Yes, we can have a default method in an interface in Java 8 and later versions.

Why Are Default Methods Required?

1. Backward Compatibility:

  • Explanation: Default methods allow interfaces to be extended with new methods without breaking the existing implementations. Before Java 8, adding a new method to an interface required all implementing classes to provide an implementation, which could break backward compatibility.
  • Example: If a new method is added to an interface with a default implementation, existing classes that implement the interface do not need to modify their code.

2. Interface Evolution:

  • Explanation: Default methods enable the evolution of interfaces over time by allowing new functionality to be added. This is particularly useful in large, widely-used interfaces where modifying all implementations would be impractical.
  • Example: The List interface in Java 8 added methods like sort() with default implementations.

3. Multiple Inheritance of Behavior:

  • Explanation: Default methods allow interfaces to inherit behavior from multiple sources. This provides some of the benefits of multiple inheritance without the associated complexity and ambiguity.
  • Example: A class can implement multiple interfaces, each providing default methods, and the class can use or override these behaviors as needed.

Example Usage

interface MyInterface {
    default void myMethod() {
        System.out.println("Default implementation");
    }
}
class MyClass implements MyInterface {  

// No need to override myMethod() unless specific behavior is needed

}

public class Main {

public static void main(String args) {

MyClass obj = new MyClass();

obj.myMethod(); // Outputs: Default implementation

}

}

Explanation:

- In this example, MyClass implements MyInterface but does not need to override myMethod() because the interface provides a default implementation.


Follow-up Question

  1. What happens if a class implements two interfaces that contain the same default method?
  2. Answer: The class must override the method to resolve the conflict, as Java does not allow ambiguity in method resolution.