Middle+
Why is a default method needed in an interface?
sobes.tech AI
Answer from AI
The method with the default modifier in a Java interface allows defining the implementation of a method directly within the interface. This is useful for:
- Adding new methods to an interface without breaking existing implementations (backward compatibility).
- Providing a base implementation that can be overridden in classes implementing the interface.
Example:
public interface MyInterface {
void existingMethod();
default void newDefaultMethod() {
System.out.println("Default implementation");
}
}
Classes implementing MyInterface can use newDefaultMethod without needing to implement it.