Sobes.tech
Junior — Middle

Can an interface that defines functionality contain default method implementations, including anonymous and named ones?

sobes.tech AI

Answer from AI

Yes, starting from Java 8, interfaces can contain methods with default implementations — so-called default methods. This allows adding new functionality to interfaces without breaking existing implementations.

Example of a default method in an interface:

public interface MyInterface {
    void existingMethod();

    default void newDefaultMethod() {
        System.out.println("Default implementation");
    }
}

As for anonymous and named methods — you cannot declare anonymous methods in an interface, but you can use lambda expressions and method references when implementing an interface. Default methods are indeed methods with implementations inside the interface, not anonymous functions.

Thus, an interface can contain default method implementations, but not anonymous methods as such.

Can an interface that defines functionality contain… - sobes.tech