What are the constructor references in Java?

Java 8Object Oriented ProgrammingProgramming

A constructor reference is just like a method reference except that the name of the method is "new". It can be created by using the "class name" and the keyword "new" with the following syntax.

Syntax

<Class-Name> :: new

In the below example, we are using java.util.function.Function. It is a functional interface whose single abstract method is the apply(). The Function interface represents an operation that takes single argument T and returns a result R.

Example

import java.util.function.*;

@FunctionalInterface
interface MyFunctionalInterface {
   Employee getEmployee(String name);
}
class Employee {
   private String name;
   public Employee(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
public class ConstructorReferenceTest {
   public static void main(String[] args) {
      MyFunctionalInterface mf = Employee :: new;   // constructor reference
      Function<String, Employee> f1 = Employee :: new;   // using Function interface
      Function<String, Employee> f2 = (name) -> new Employee(name);   // Lambda Expression

      System.out.println(mf.getEmployee("Raja").getName());
      System.out.println(f1.apply("Adithya").getName());
      System.out.println(f2.apply("Jaidev").getName());
   }
}

Output

Raja
Adithya
Jaidev
raja
Published on 13-Dec-2019 07:42:41
Advertisements