Phase 11 of 20 · Topic 11.3

Private Methods in Interfaces (Java 9+)

1Concept

Java 9 introduced private and private static methods inside interfaces. They allow encapsulating common helper logic shared between multiple default methods without exposing those helpers as public API to consumers.

2Architecture Diagram

[ Public Default Method A ] ---
                                 \---> [ Private Helper Method ] (Encapsulated inside interface)
[ Public Default Method B ] ---/

3Code Example

Core Java
public class PrivateInterfaceMethodsDemo {
    interface DataIngestionService {
        default void ingestJson(String payload) {
            validatePayload(payload);
            System.out.println("Ingesting JSON stream: " + payload);
        }

        default void ingestXml(String payload) {
            validatePayload(payload);
            System.out.println("Ingesting XML stream: " + payload);
        }

        // Private helper method encapsulating shared validation
        private void validatePayload(String payload) {
            if (payload == null || payload.isBlank()) {
                throw new IllegalArgumentException("Payload cannot be empty");
            }
        }
    }

    static class Pipeline implements DataIngestionService {}

    public static void main(String[] args) {
        Pipeline pipeline = new Pipeline();
        pipeline.ingestJson("{\"status\": \"OK\"}");
        pipeline.ingestXml("<status>OK</status>");
    }
}

4Expected Output

Ingesting JSON stream: {"status": "OK"}
Ingesting XML stream: <status>OK</status>

5Key Takeaways

  • Private methods inside interfaces must have a method body.
  • Private interface methods can be either instance (`private`) or static (`private static`).
  • Prevents interface code duplication without leaking helper methods into the public API.