Junior — Middle
What is the purpose of a method with a default implementation in an interface?.
sobes.tech AI
Answer from AI
The default method implementation in an interface allows defining the method body directly within the interface. This is useful for:
- Adding new methods to an interface without breaking existing implementations.
- Providing a base implementation that can be overridden in classes.
Example:
public interface MyInterface {
default void defaultMethod() {
System.out.println("Default implementation");
}
}
public class MyClass implements MyInterface {
// Can use the default implementation or override it
}
Thus, default methods increase the flexibility of interfaces and facilitate API evolution.