Junior — Middle
Why was the ability to specify a default implementation for methods within interfaces introduced in Java 8?
sobes.tech AI
Answer from AI
In Java 8, the ability to define default implementations for interface methods (default methods) was introduced to ensure backward compatibility when extending interfaces. Previously, if a new method was added to an interface, all classes implementing it had to implement this method, which often required changing many classes.
With default methods, new functionality can be added to an interface with a default implementation, without breaking existing code. This is especially important for the development of large APIs and libraries.
Example:
public interface MyInterface {
void existingMethod();
default void newDefaultMethod() {
System.out.println("Default implementation");
}
}