Commit 1c71d02
committed
feat(constructor-reference): demonstrate using Supplier with Example::new for lazy object creation
What
- Added `Example` class with a no-argument constructor that prints a message when invoked.
- Added `ConstructorReference` class to show:
- Declaring a `Supplier<Example>` functional interface.
- Assigning the constructor reference `Example::new` to it.
- Using `supplier.get()` to trigger actual object creation.
Why
- Shows how constructor references integrate seamlessly with functional interfaces like `Supplier<T>`.
- Demonstrates **lazy instantiation**: object is not created until `get()` is explicitly invoked.
- Reinforces that method/constructor references are syntactic sugar for lambdas, improving readability.
Logic
1. `Supplier<Example> supplier = Example::new;`
- Binds the no-arg constructor of `Example` to the `Supplier` functional interface.
- Equivalent lambda: `() -> new Example()`.
2. `Example ex = supplier.get();`
- Calls `get()`, which internally executes `new Example()`.
- Prints `"Example constructor called!"` because of the constructor side-effect.
Real-life applications
- Lazy initialization of heavy resources (e.g., database connections, file readers).
- Factories for object creation in dependency injection frameworks.
- Stream pipelines where new objects are created on-demand without verbose lambdas.
Notes
- `Supplier<T>` is a built-in functional interface from `java.util.function`.
- Constructor reference works when the constructor signature matches the functional interface’s abstract method:
- Here, `Supplier<T>` has `T get()` → matches `Example()` constructor.
- Key benefit: **cleaner and more expressive code** than explicitly writing lambdas or anonymous classes.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent e352870 commit 1c71d02
File tree
1 file changed
+2
-2
lines changed- Java 8 Crash Course/Functional Interface/Static Methods/src
1 file changed
+2
-2
lines changedLines changed: 2 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
8 | | - | |
| 8 | + | |
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
16 | | - | |
| 16 | + | |
0 commit comments