Java 8: Difference between method reference Bound Receiver and UnBound Receiver

I am trying to use Java 8 method references in my code. There are four types of method references available.

  1. Static method reference.
  2. Instance Method (Bound receiver).
  3. Instance Method (UnBound receiver).
  4. Constructor reference.

With Static method reference and Constructor reference i have no problem, but Instance Method (Bound receiver) and Instance Method (UnBound receiver) really confused me. In Bound receiver, we are using an Object reference variable for calling a method like:

objectRef::Instance Method

In UnBound receiver we are using Class name for calling a method like:

ClassName::Instance Method.

I have the following question:

  1. What is the need for different types of method references for Instance Methods?
  2. What is the difference between Bound and Unbound receiver method references?
  3. Where should we use Bound receiver and where should we use Unbound receiver?

I also found the explanation of Bound and Unbound receiver from Java 8 language features books, but was still confused with the actual concept.

Jon Skeet
people
quotationmark

Basically, unbound receivers allow you to use instance methods as if they were static methods with a first parameter of the declaring type - so you can use them as functions by passing in whatever instance you want. With a bound receiver, the "target" instance is effectively part of the function.

An example might make this clearer:

import java.util.function.*;

public class Test {

    private final String name;

    public Test(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Test t1 = new Test("t1");
        Test t2 = new Test("t2");

        Supplier<String> supplier = t2::method;
        Function<Test, String> function = Test::method;

        // No need to say which instance to call it on -
        // the supplier is bound to t2            
        System.out.println(supplier.get());

        // The function is unbound, so you need to specify
        // which instance to call it on
        System.out.println(function.apply(t1));
        System.out.println(function.apply(t2));
    }

    public String method() {
        return name;
    }
}

people

See more on this question at Stackoverflow