This tutorial explains the new Java 8 feature known as constructor reference. It starts off with explaining what is a constructor reference by showing its structure and an example. Next, the tutorial shows an example scenario where constructor references can be applied for instantiating objects from an object factory.
(Note – If you are new to the concept of method references then I would recommend that first refer the method references tutorialRead Method References Tutorial.)
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 –
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
Read tutorial on Factory Design Pattern.
public Interface EmployeeFactory{ public abstract Employee getEmployee(String name, Integer age); }
EmployeeFactory
interface has a single abstract method hence it is a Functional InterfaceRead Tutorial on Functional Interfaces.
STEP 3 – The client side code to invoke EmployeeFactory
to create Employee
instances would be as follows –
EmployeeFactory empFactory=Employee::new; Employee emp= empFactory.getEmployee("John Hammond", 25);
- The Constructor Reference of
Employee
is assigned to an instance ofEmployeeFactory
calledempFactory
. This is possible because the function descriptorRead tutorial on Java 8 Function Descriptors ofEmployee
constructor is same as that of the abstract method of the Functional InterfaceEmployeeFactory
i.e.
(String, Integer) ->Employee.
- Then the
getEmployee
method ofempFactory
is called with John’s name and age which internally calls the constructor ofEmployee
and a newEmployee
instanceemp
is created.
Summary: In the above tutorial we understood constructor references by first understanding their definition/structure. Next we saw examples for defining a constructor reference for actual usage and then saw an example practical scenario where constructor references can be used.
