-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathprivate-interface-methods.yaml
More file actions
60 lines (60 loc) · 1.78 KB
/
private-interface-methods.yaml
File metadata and controls
60 lines (60 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
---
id: 13
slug: "private-interface-methods"
title: "Private interface methods"
category: "language"
difficulty: "intermediate"
jdkVersion: "9"
oldLabel: "Java 8"
modernLabel: "Java 9+"
oldApproach: "Duplicated Logic"
modernApproach: "Private Methods"
oldCode: |-
interface Logger {
default void logInfo(String msg) {
System.out.println(
"[INFO] " + timestamp() + msg);
}
default void logWarn(String msg) {
System.out.println(
"[WARN] " + timestamp() + msg);
}
}
modernCode: |-
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));
}
}
summary: "Extract shared logic in interfaces using private methods."
explanation: "Java 9 allows private methods in interfaces, enabling you to share code\
\ between default methods without exposing implementation details to implementing\
\ classes."
whyModernWins:
- icon: "🧩"
title: "Code reuse"
desc: "Share logic between default methods without duplication."
- icon: "🔐"
title: "Encapsulation"
desc: "Implementation details stay hidden from implementing classes."
- icon: "🧹"
title: "DRY interfaces"
desc: "No more copy-paste between default methods."
support:
state: "available"
description: "Widely available since JDK 9 (Sept 2017)"
prev: "language/diamond-operator"
next: "language/pattern-matching-switch"
related:
- "language/compact-source-files"
- "language/flexible-constructor-bodies"
- "language/type-inference-with-var"
docs:
- title: "Private Interface Methods"
href: "https://openjdk.org/jeps/213"