✅ We can assign
greeting::length
toSupplier<Integer>
because their method signatures match.
🔗 Let’s Compare the Signatures
Supplier
Functional Interface
@FunctionalInterface
public interface Supplier<T> {
T get();
}
- Method signature:
Integer get()
Method Reference — greeting::length
public int length()
- This method belongs to
String
, andgreeting
is a specificString
object. - It takes no arguments and returns
int
(which gets autoboxed toInteger
).
✅ Matching the Signature
Expected (Supplier<Integer>) | Actual (greeting::length) | Matching? |
---|---|---|
Integer get() | int length() | ✔️ Yes (autoboxed to Integer) |
📣 Key Rule for Method References
Method Reference = Allowed only if it fits the target functional interface’s method signature.
This is why:
Supplier<Integer> bound = greeting::length; // Works
But this would fail:
Function<String, Integer> func = greeting::length; // ❌ Doesn't match Function<T, R>
🔥 Pro Tip for Interviews
✅ When asked “Why does this work?”, just say:
“The method reference fits the functional interface’s method signature.”