Senior
Why is a default method needed in an interface?
sobes.tech AI
Answer from AI
A default method in an interface is used to provide an implementation of a method directly within the interface, without forcing all classes that implement it to override this method.
This allows:
- Adding new methods to an interface without breaking existing implementations.
- Providing a default behavior that can be overridden if necessary.
For example, in Java 8, default methods enable extending interfaces without breaking backward compatibility.
Example in Java:
public interface Logger {
void log(String message);
default void logError(String error) {
log("ERROR: " + error);
}
}
Here, logError has a default implementation, and classes implementing Logger may not need to write this method if the default behavior suits them.