All 15 Functional Interfaces & Method References questions
More in Functional Interfaces & Method References
Advertisement
Java › Functional Interfaces & Method References

What are the four kinds of method references in Java (static, instance-bound, instance-unbound, and constructor), and how does the compiler determine which form applies?

Intermediate

Answer

Static method reference (ClassName::staticMethod) refers to a static method; bound instance method reference (instance::method) refers to a specific, already-existing object's instance method; unbound instance method reference (ClassName::instanceMethod) refers to an instance method where the first functional interface parameter becomes the receiver object the method is called on; constructor reference (ClassName::new) refers to a constructor -- the compiler determines which form applies based on the functional interface's method signature being targeted, matching parameter types and count against the referenced method/constructor's own signature.
// Static
Function<String, Integer> parse = Integer::parseInt;

// Bound instance (specific object 'str')
String str = "hello";
Supplier<Integer> len = str::length;

// Unbound instance (first param becomes the receiver)
Function<String, Integer> len2 = String::length;  // equivalent to s -> s.length()

// Constructor
Supplier<ArrayList<String>> listMaker = ArrayList::new;
Real-world example A stream pipeline transforming a list of raw strings into parsed integers uses the static method reference Integer::parseInt, while a separate pipeline extracting each string's length uses the unbound instance reference String::length, both more concise and readable than the equivalent explicit lambda expressions.

Common follow-ups: How would you write the unbound instance method reference example as an equivalent explicit lambda?;What happens if a method reference is ambiguous between multiple overloaded methods with the same name?