Method References

 
/**
 * METHOD REFERENCES (::)
 * ----------------------
 * Method references are a compact syntax for lambdas that
 * simply call an existing method.
 * 
 * Insteed of writting:
 *      x -> someMethod(x)
 * 
 * We can write:
 *      ClassName::someMethod
 * 
 * IMPORTANT:
 * ----------
 *  - Method refrences do NOT call the method
 *  - They only reference it
 *  - The method is executed by the functionl interface
 * 
 * Method references work only when:
 *  - The method signature matches the funtional interface
 * 
 * WHY System.out::println WORKS?
 * ------------------------------
 * forEach() espects a Consumer<String> which has:
 *      void accept(String s);
 * 
 * println() has the same shape:
 *      void println(String s);
 * 
 * So Java can safely connect them.
 */

package com.minte9.lambdas.method_references;

import java.util.Arrays;
import java.util.List;

public class MethodReferences {
    public static void main(String[] args) {
        
        List<String> names = Arrays.asList("Ana", "Bob", "John");

        // ---------------------------------------
        // Lambda version
        // ---------------------------------------
        names.forEach(n -> System.out.println(n));

        // ---------------------------------------
        // Method reference version
        // ---------------------------------------
        names.forEach(System.out::println);
    }
}






Questions and answers:
Clink on Option to Answer




1. What is a method reference?

  • a) A method call that executes immediately
  • b) A compact reference to an existing method

2. When can a lambda be replaced with a method reference?

  • a) When the method signature matches the functional interface
  • b) When the method name is the same

3. Do method references execute the method immediately?

  • a) Yes, they call the method directly
  • b) No, they only reference the method

4. Why does System.out::println work with forEach()?

  • a) Because println matches the Consumer method signature
  • b) Because println is a static method

5. What does a method reference replace?

  • a) A constructor
  • b) A lambda that only calls one method

6. Which statement about method references is TRUE?

  • a) They improve readability when behavior already exists
  • b) They can replace any lambda expression

7. Who actually executes the referenced method?

  • a) The class that defines the method
  • b) The functional interface implementation


References: