How to implement a constructor reference with one or more arguments in Java?


A method reference can also be applicable to constructors in Java 8. A constructor reference can be created using the class name and a new keyword. The constructor reference can be assigned to any functional interface reference that defines a method compatible with the constructor.

Syntax

<Class-Name>::new

Example of Constructor Reference with One Argument

import java.util.function.*;

@FunctionalInterface
interface MyFunctionalInterface {
   Student getStudent(String name);
}
public class ConstructorReferenceTest1 {
   public static void main(String[] args) {
      MyFunctionalInterface mf = Student::new;

      Function<Sttring, Student> f1 = Student::new;    // Constructor Reference
      Function<String, Student> f2 = (name) -> new Student(name);

      System.out.println(mf.getStudent("Adithya").getName());
      System.out.println(f1.apply("Jai").getName());
      System.out.println(f2.apply("Jai").getName());
   }
}

// Student class
class Student {
   private String name;
   public Student(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Output

Adithya
Jai
Jai


Example of Constructor Reference with Two Arguments

import java.util.function.*;

@FunctionalInterface
interface MyFunctionalInterface {
   Student getStudent(int id, String name);
}
public class ConstructorReferenceTest2 {
   public static void main(String[] args) {
      MyFunctionalInterface mf = Student::new;    //  Constructor Reference

      BiFunction<Integer, String, Student> f1 = Student::new;
      BiFunction<Integer, String, Student> f2 = (id, name) -> new Student(id,name);

      System.out.println(mf.getStudent(101, "Adithya").getId());
      System.out.println(f1.apply(111, "Jai").getId());
      System.out.println(f2.apply(121, "Jai").getId());
   }
}

// Student class
class Student {
   private int id;
   private String name;
   public Student(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Output

101
111
121

Updated on: 14-Jul-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements