Commit d82de2d
committed
feat: demonstrate constructor reference using functional interface
WHAT was done:
- Created a functional interface `MyConstructor` with a single abstract method `display(String str)`.
- Implemented a class `ConstructerAsMethodReference` with a constructor that takes a `String` and prints it in uppercase.
- Used a method reference (`ConstructerAsMethodReference::new`) to map the interface method `display()` to the class constructor.
- Invoked the functional interface method to trigger object creation and execution.
KEY LEARNINGS:
1. Constructor References:
- Syntax: `ClassName::new`
- Used to map a constructor to a functional interface method.
- Acts like a bridge between a functional interface and object instantiation.
2. Functional Interface:
- `MyConstructor` defines `display(String str)` as a SAM (Single Abstract Method).
- Compatible with the constructor of `ConstructerAsMethodReference` which takes a `String`.
3. Flow:
- `m1 = ConstructerAsMethodReference::new` → Assigns constructor reference.
- `m1.display("...")` → Invokes the constructor indirectly via the functional interface.
4. Benefits:
- Cleaner, more expressive code than using `new` directly inside lambda expressions.
- Improves readability in functional programming and stream pipelines.
REAL-LIFE APPLICATIONS:
- ✅ Object creation in Java Streams (`map(ClassName::new)`).
- ✅ Factory patterns where constructors can be passed as parameters.
- ✅ Dependency injection frameworks to decouple object instantiation logic.
RULE OF THUMB:
- Use constructor references when a functional interface method matches a constructor signature.
- Prefer `ClassName::new` over verbose lambdas `(str -> new ClassName(str))` for cleaner code.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent cc5aa65 commit d82de2d
File tree
1 file changed
+40
-8
lines changed- Section22Lambda Expressions/src
1 file changed
+40
-8
lines changedLines changed: 40 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
| 1 | + | |
| 2 | + | |
| 3 | + | |
4 | 4 | | |
| 5 | + | |
5 | 6 | | |
6 | | - | |
7 | | - | |
| 7 | + | |
8 | 8 | | |
9 | 9 | | |
10 | 10 | | |
11 | | - | |
12 | | - | |
| 11 | + | |
13 | 12 | | |
14 | 13 | | |
15 | 14 | | |
16 | 15 | | |
17 | | - | |
| 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 | + | |
0 commit comments