Constructor References in Java 8

In this tutorial we will explain a new feature of Java 8 known as constructor reference. This is same as method reference feature in Java 8.

Constructors are a special kind of methods which are responsible for Object initialization. So we can make Constructor Method References like any other method reference. The syntax for constructor reference is as following:

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

You can create constructor references with array types. for example, if you want to create a integer array, the constructor reference is "int[] :: new" and the parameter is length of the array.

The equivalent lambda expression is :

 x -> new int[x];

We can assign a constructor reference to any functional interface which has a method compatible with the constructor. 

Following is an example usage of Constructor References:

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

package com.tuturself.consref;

import java.util.Random;

public class Employee {

	int employeeId;
	String name;
	String gender;

	public Employee(String name, String gender) {
		employeeId = new Random().nextInt(50) + 1;
		this.name = name;
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Employee: [employeeId=" + employeeId 
                   +"\n name=" + name + "\n gender=" + gender + "]";
	}
}

Now lets create a factory interface for employees called EmployeeFactory. The getEmployee() method of EmployeeFactory will returns an employee instance. This is an example of a Functional Interface.

package com.tuturself.consref;

public interface EmployeeFactory {

	public abstract Employee getEmployee(String name, String gender);
}

The client side code to invoke EmployeeFactory to create Employee instances would be as follows:

package com.tuturself.consref;

public class Test {

	public static void main(String[] args) {
		EmployeeFactory empFactory = Employee::new;
		Employee emp = empFactory.getEmployee("Ninja Panda", "MALE");
		System.out.println(emp);
	}
}

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, String) ->Employee

core java 12 Java-8 12

FOLLOW US ON LinkedIn



Explore Tutu'rself