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:
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 –
STEP 2 – Now lets create a factory interface for employees called
getEmployee() method of
EmployeeFactory will return an employee instance as per the normal design of factory pattern
Read tutorial on Factory Design Pattern.
EmployeeFactoryinterface 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 –
- The Constructor Reference of
Employeeis assigned to an instance of
empFactory. This is possible because the function descriptorRead tutorial on Java 8 Function Descriptors of
Employeeconstructor is same as that of the abstract method of the Functional Interface
(String, Integer) ->Employee.
- Then the
empFactoryis called with John’s name and age which internally calls the constructor of
Employeeand a new
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.