All 15 Interfaces & Abstract Classes questions
More in Interfaces & Abstract Classes
Advertisement
Back to results for “Interfaces & Abstract Classes”
Java › Interfaces & Abstract Classes

What are private methods on an interface (introduced in Java 9), and what specific problem do they solve regarding code duplication between multiple default methods?

Advanced

Answer

Private interface methods (both regular private instance methods and private static methods) let an interface share common implementation logic BETWEEN its own default methods without exposing that shared logic as part of the interface's own public contract -- before Java 9, if two default methods on the same interface needed to share some common helper logic, that logic either had to be duplicated in both default methods, or awkwardly exposed as a public (or default) method that implementing classes could see and potentially override unexpectedly, neither being an ideal solution; private methods solve this cleanly by allowing genuine internal implementation-detail sharing exactly as private methods do within a regular class.
public interface Validator {
    default boolean isValidEmail(String email) {
        return matches(email, "email-pattern") && !isEmpty(email);
    }
    default boolean isValidPhone(String phone) {
        return matches(phone, "phone-pattern") && !isEmpty(phone);
    }

    private boolean isEmpty(String s) {  // shared helper, NOT part of the public interface contract
        return s == null || s.isBlank();
    }
    private boolean matches(String s, String patternKey) {  // shared helper
        return true;  // simplified
    }
}
Real-world example A Validator interface's two default methods (isValidEmail and isValidPhone) share common null/blank-checking logic factored into a private isEmpty() helper method, keeping this shared logic entirely internal to the interface's own implementation without exposing it as part of the interface's public API surface that implementing classes could see or override.

Common follow-ups: Why weren't private interface methods included in the original Java 8 default methods feature, requiring a separate Java 9 addition?;Can a private interface method be called from an implementing class's own code, or only from within the interface's own default/static methods?