Differences between Method Reference and Constructor Reference in Java?

Java 8Object Oriented ProgrammingProgramming

A method reference is similar to lambda expression used to refer a method without invoking it while constructor reference used to refer to the constructor without instantiating the named class. A method reference requires a target type similar to lambda expressions. But instead of providing an implementation of a method, they refer to a method of an existing class or object while a constructor reference provides a different name to different constructors within a class.

syntax - Method Reference

<Class-Name>::<instanceMethodName>

Example

import java.util.*;

public class MethodReferenceTest {
   public static void main(String[] args) {
      List<String> names = new ArrayList<String>();
      List<String> selectedNames = new ArrayList<String>();

      names.add("Adithya");
      names.add("Jai");
      names.add("Raja");
      names.forEach(selectedNames :: add); // instance method reference

      System.out.println("Selected Names:");
      selectedNames.forEach(System.out :: println);
   }
}

Output

Selected Names:
Adithya
Jai
Raja


Syntax -Constructor Reference

<Class-Name>::new

Example

@FunctionalInterface
interface MyInterface {
   public Student get(String str);
}
class Student {
   private String str;
   public Student(String str) {
      this.str = str;
      System.out.println("The name of the student is: " + str);
   }
}
public class ConstrutorReferenceTest {
   public static void main(String[] args) {
      MyInterface constructorRef = Student :: new;   // constructor reference
      constructorRef.get("Adithya");
   }
}

Output

The name of the student is: Adithya
raja
Published on 27-Dec-2019 15:44:04
Advertisements