Skip to content

Commit 1c71d02

Browse files
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

1 file changed

+2
-2
lines changed

JAVA8/ConstructorReference/src/ConstructorReference.java renamed to Java 8 Crash Course/Functional Interface/Static Methods/src/ConstructorReferenceDmo.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ class Example {
55
System.out.println("Example constructor called!");
66
}
77
}
8-
public class ConstructorReference {
8+
public class ConstructorReferenceDmo {
99
public static void main(String[] args) {
1010
// Using a constructor reference
1111
Supplier<Example> supplier = Example::new;
1212

1313
// Calling get() will invoke the constructor
1414
Example ex = supplier.get();
1515
}
16-
}
16+
}

0 commit comments

Comments
 (0)