Private interface methods
Code Comparison
interface Logger {
default void logInfo(String msg) {
System.out.println(
"[INFO] " + timestamp() + msg);
}
default void logWarn(String msg) {
System.out.println(
"[WARN] " + timestamp() + msg);
}
}
interface Logger {
private String format(String lvl, String msg) {
return "[" + lvl + "] " + timestamp() + msg;
}
default void logInfo(String msg) {
IO.println(format("INFO", msg));
}
default void logWarn(String msg) {
IO.println(format("WARN", msg));
}
}
Why the modern way wins
๐งฉ
Code reuse
Share logic between default methods without duplication.
๐
Encapsulation
Implementation details stay hidden from implementing classes.
๐งน
DRY interfaces
No more copy-paste between default methods.
Old Approach
Duplicated Logic
Modern Approach
Private Methods
JDK Support
Private interface methods
Available
Widely available since JDK 9 (Sept 2017)
How it works
Java 9 allows private methods in interfaces, enabling you to share code between default methods without exposing implementation details to implementing classes.
Related Documentation
Proof