Junior — Middle
Is it possible to define the implementation of a method inside an interface in a programming language?
sobes.tech AI
Answer from AI
Yes, in modern versions of Java (starting from Java 8), it became possible to define method implementations inside interfaces using default methods and static methods.
- Default methods allow you to specify a standard implementation that all classes implementing the interface can use or override if necessary.
- Static methods in interfaces are methods that belong to the interface itself and are called through the interface name.
Example:
public interface MyInterface {
void abstractMethod(); // regular abstract method
default void defaultMethod() {
System.out.println("Default implementation");
}
static void staticMethod() {
System.out.println("Interface static method");
}
}
This allows extending interfaces without breaking existing code by adding new methods with implementations.