Sobes.tech
Junior — Middle

Is it possible to declare private methods inside an interface in Java functional interfaces?

sobes.tech AI

Answer from AI

In Java, starting from version 9, private methods can be declared in interfaces. This allows avoiding code duplication in default and static interface methods, enhancing encapsulation.

In functional interfaces (interfaces with a single abstract method), declaring private methods is also permitted, but they do not affect the functionality of the interface as a functional one; they serve for internal code organization.

Example:

@FunctionalInterface
public interface MyFunction {
    void apply();

    private void helper() {
        System.out.println("Private method inside interface");
    }

    default void defaultMethod() {
        helper();
    }
}

Thus, private methods inside interfaces are allowed and useful for structuring code, including in functional interfaces.