-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNestedInterface.java
More file actions
184 lines (162 loc) · 6.53 KB
/
Copy pathNestedInterface.java
File metadata and controls
184 lines (162 loc) · 6.53 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package Phase3_ObjectOrientation.Interfaces;
import java.util.Iterator;
/**
* Nested Interfaces
* -----------------
* An interface declared INSIDE another type (a class or another interface) is
* a NESTED INTERFACE. It is a way to scope a contract to the type that owns
* it - the interface "belongs" to the outer type both conceptually and in
* its fully qualified name.
* <p>
*
* class List {
* interface Iterator { ... } // nested
* }
* // fully qualified name: List.Iterator
* <p>
*
* Two Flavours
* ------------
* 1. Nested inside a CLASS
* - Implicitly STATIC (every nested type inside an interface is also
* implicitly static; inside a class, the `static` keyword is allowed
* for clarity but is the default for nested interfaces too).
* - Can be private / protected / package-private / public (controls
* who outside the file can see it).
* <p>
*
* 2. Nested inside an INTERFACE
* - Implicitly PUBLIC and STATIC.
* <p>
*
* Why Nest an Interface?
* ----------------------
* - LOGICAL GROUPING - the interface is meaningful only in the context of
* the outer type (Map.Entry, ChronoLocalDate.Era, Stream.Builder).
* - NAMESPACE HYGIENE - prevents top-level name pollution.
* - ACCESS CONTROL - a `private` nested interface is invisible to other
* files, useful for internal abstractions inside a class.
* <p>
*
* JDK Examples
* ------------
* Map.Entry<K,V> - per-entry view of a Map
* Iterable.Iterator<T> - (Iterator is now a top-level interface,
* but historically it was nested)
* AbstractMap.SimpleEntry<K,V> - a class implementing Map.Entry
* Builder patterns - inner Builder interface owned by the type
* <p>
*
* Rules To Remember
* -----------------
* - You CANNOT instantiate an interface directly - nested or not.
* - Use the qualified name to refer to it from outside:
* <p>
*
* Outer.NestedInterface nested = new Outer.NestedInterface() { ... };
* <p>
*
* - A nested interface can extend other interfaces, just like a top-level one.
* - Inside the outer type's body you refer to it by its simple name.
*/
public class NestedInterface {
// ============================================================
// 1) Interface nested inside a CLASS
// ============================================================
static class SimpleList<E> {
/**
* A read-only cursor over a SimpleList.
* It is meaningful only in the context of SimpleList, so we nest it.
*/
public interface Cursor<E> {
boolean hasNext();
E next();
}
private final Object[] data;
public SimpleList(Object[] data) { this.data = data; }
/** Returns a cursor implementing the nested interface. */
@SuppressWarnings("unchecked")
public Cursor<E> cursor() {
return new Cursor<E>() {
int i = 0;
@Override public boolean hasNext() { return i < data.length; }
@Override public E next() { return (E) data[i++]; }
};
}
}
// ============================================================
// 2) Interface nested inside another INTERFACE
// ============================================================
interface Repository<T> {
/**
* A SAVE callback contract. Nested inside Repository because it only
* makes sense in that context. Implicitly public + static.
*/
interface SaveListener<T> {
void saved(T value);
}
void save(T value, SaveListener<T> listener);
}
static class InMemoryRepo<T> implements Repository<T> {
@Override
public void save(T value, SaveListener<T> listener) {
// ... persist value somewhere ...
listener.saved(value);
}
}
// ============================================================
// 3) PRIVATE nested interface - hidden from the outside world
// ============================================================
static class Cache {
/**
* `private` nested interface - usable only by Cache itself. Other
* classes cannot even mention the type Cache.Eviction.
*/
private interface Eviction {
String pick();
}
private final Eviction policy;
public Cache() {
// Anonymous implementation of the private nested interface.
this.policy = () -> "random-key";
}
public String evict() { return policy.pick(); }
}
public static void main(String[] args) {
section("1) Interface nested in a class - SimpleList.Cursor");
SimpleList<String> list = new SimpleList<>(new Object[]{"a", "b", "c"});
SimpleList.Cursor<String> c = list.cursor();
while (c.hasNext()) System.out.print(c.next() + " ");
System.out.println();
section("2) Interface nested in an interface - Repository.SaveListener");
Repository<String> repo = new InMemoryRepo<>();
repo.save("hello", v -> System.out.println("saved: " + v)); // lambda
section("3) Private nested interface - invisible from outside");
Cache cache = new Cache();
System.out.println("evict() = " + cache.evict());
// Cache.Eviction e = ... // ERROR - Eviction has private access
section("4) Real-world example - Map.Entry");
java.util.Map<String, Integer> m = java.util.Map.of("a", 1, "b", 2);
for (java.util.Map.Entry<String, Integer> e : m.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
// Map.Entry is the nested interface; getKey()/getValue() come from it.
// OUTPUT
// ====== 1) Interface nested in a class - SimpleList.Cursor ======
// a b c
// ====== 2) Interface nested in an interface - Repository.SaveListener ======
// saved: hello
// ====== 3) Private nested interface - invisible from outside ======
// evict() = random-key
// ====== 4) Real-world example - Map.Entry ======
// a -> 1
// b -> 2
}
private static void section(String title) {
System.out.println("\n====== " + title + " ======");
}
// A small unused import-style note: `Iterator` referenced here only to
// anchor the import - real JDK example is in main().
@SuppressWarnings("unused")
private static Iterator<String> unused;
}