Private interface methods
Extract shared logic in interfaces using private methods.
Code Comparison
✕ Java 8
interface Logger {
default void logInfo(String msg) {
System.out.println(
"[INFO] " + timestamp() + msg);
}
default void logWarn(String msg) {
System.out.println(
"[WARN] " + timestamp() + msg);
}
}
✓ Java 9+
interface Logger {
private String format(String lvl, String msg) {
return "[" + lvl + "] " + timestamp() + msg;
}
default void logInfo(String msg) {
System.out.println(format("INFO", msg));
}
default void logWarn(String msg) {
System.out.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
Since JDK
9
Difficulty
intermediate
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.