Junior — Middle
Explain what it means to have a method with a default implementation inside an interface in a programming language.
sobes.tech AI
Answer from AI
A default method inside a Java interface is a method that has an implementation within the interface itself. This allows adding new methods to interfaces without breaking existing implementations.
For example, if an interface is extended with a new method with a default implementation, existing classes automatically inherit this implementation and do not need to be changed.
Example:
public interface MyInterface {
void existingMethod();
default void newDefaultMethod() {
System.out.println("This is a default method");
}
}
Thus, default methods increase flexibility and backward compatibility of interfaces.