0Pricing
Java Academy · Lesson

Instance Method References on a Specific Instance

Capture a specific object and reference one of its instance methods for callbacks and listeners.

Specific Instance Reference

An instance method reference on a specific instance captures a particular object and references one of its methods. Syntax: instance::methodName.

// System.out is a specific PrintStream instance
List<String> names = List.of("Alice","Bob","Carol");
names.forEach(System.out::println); // System.out is the captured instance

Capturing a Custom Object Instance

Any object can be captured. The method reference borrows the instance at the time of creation:

class Greeter {
    private String prefix;
    Greeter(String prefix) { this.prefix = prefix; }
    String greet(String name) { return prefix + ", " + name + "!"; }
}

Greeter g = new Greeter("Hello");
java.util.function.Function<String, String> greetFn = g::greet;

System.out.println(greetFn.apply("Alice")); // Hello, Alice!
System.out.println(greetFn.apply("Bob"));   // Hello, Bob!

All lessons in this course

  1. Static Method References
  2. Instance Method References on a Specific Instance
  3. Arbitrary-Instance Method References
  4. Constructor References
← Back to Java Academy