Middle
What is a default method in an interface?
sobes.tech AI
Answer from AI
This is a method in an interface marked with the keyword default and having a default implementation.
Introduced in Java 8 to solve the "compatibility" problem of interfaces when adding new methods. They allow adding a new method to an existing interface without breaking classes that implement this interface. Implementing classes can use the default implementation or override it.
Main features:
- Allow a method body in an interface.
- Enable adding new methods to interfaces without forcing all implementing classes to change.
- Can be overridden in implementing classes.
- Can call other interface methods (including abstract ones).
- Cannot be static or final (unlike static interface methods).
Example:
// Interface before adding a default method
interface MyInterface {
void existingMethod();
}
// Class implementing the old interface
class MyClass implements MyInterface {
@Override
public void existingMethod() {
System.out.println("Existing implementation");
}
}
// Interface with added default method
interface MyInterfaceWithDefault {
void existingMethod();
// New default method
default void newDefaultMethod() {
System.out.println("Default implementation of new method");
}
}
// Existing class can implement the new interface without changes
class MyClassUsingDefault implements MyInterfaceWithDefault {
@Override
public void existingMethod() {
System.out.println("Existing implementation");
}
// newDefaultMethod() is inherited automatically
}
// New class can override the default method
class MyClassOverridingDefault implements MyInterfaceWithDefault {
@Override
public void existingMethod() {
System.out.println("Existing implementation");
}
@Override
public void newDefaultMethod() {
System.out.println("Overridden implementation of new method");
}
}
Multiple inheritance conflicts: If a class implements two interfaces with the same default method, the compiler will give an error, and the class must override this method. The class can call the implementation from a specific interface using the syntax InterfaceName.super.methodName().