Skip to main content
Java 9 · Topic 3 of 6

Private interface methods

Definition​

Since Java 9 an interface can have private methods. They let several default methods share code inside the interface without exposing that code to anyone else.

Example code​

Two default methods sharing one private helper

interface Logger {
default void info(String message) { System.out.println(format("INFO", message)); }
default void error(String message) { System.out.println(format("ERROR", message)); }

private String format(String level, String message) { // hidden helper, Java 9
return "[" + level + "] " + message;
}
}

class Demo {
public static void main(String[] args) {
Logger logger = new Logger() { };
logger.info("started");
logger.error("something failed");
}
}

// Output:
// [INFO] started
// [ERROR] something failed

Finished this page? Track your progress (saved only in your browser).