Sunday, September 29, 2019

Constructor References Java 8

What are Constructor References: Constructor Introduced in Java 8, constructor references are specialized form of method references which refer to the constructors of a class. Constructor References can be created using the Class Name and the keyword new with the following syntax –
Syntax of Constructor References: <ClassName>::new

Constructor Reference Example: If you want reference to the constructor of wrapper class Integer, then you can write something like this –
Supplier<Integer> integerSupplier = Integer::new

Example usage of Constructor References in code

STEP 1 – Let us define an Employee class with a constructor having 2 parameters as shown below –

Employee.java
public class Employee{
 String name;
 Integer age;
 //Contructor of employee
 public Employee(String name, Integer age){
  this.name=name;
  this.age=age;
 }
}

STEP 2 – Now lets create a factory interface for employees called EmployeeFactory. getEmployee() method of EmployeeFactory will return an employee instance as per the normal design of factory pattern.


Interface EmployeeFactory.java

public Interface EmployeeFactory{
 public abstract Employee getEmployee(String name, Integer age);
}

Note – Since EmployeeFactory interface has a single abstract method hence it is a Functional Interface.


STEP 3 – The client side code to invoke EmployeeFactory to create Employee instances would be as follows –

Client-side code for invoking Factory interface

EmployeeFactory empFactory=Employee::new;
Employee emp= empFactory.getEmployee("John Hammond", 25);

Explanation of the code

The Constructor Reference of Employee is assigned to an instance of EmployeeFactory called empFactory. This is possible because the function descriptor of Employee constructor is same as that of the abstract method of the Functional Interface EmployeeFactory i.e.
(String, Integer) ->Employee.

Then the getEmployee method of empFactory is called with John’s name and age which internally calls the constructor of Employee and a new Employee instance emp is created.

No comments:

Post a Comment