
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Constructor References in Java
A constructor reference is just like a method reference except that the name of the method is "new". It can be created by using the "class name" and the keyword "new" with the following syntax.
Syntax
<Class-Name> :: new
In the below example, we are using java.util.function.Function. It is a functional interface whose single abstract method is the apply(). The Function interface represents an operation that takes single argument T and returns a result R.
Example
import java.util.function.*; @FunctionalInterface interface MyFunctionalInterface { Employee getEmployee(String name); } class Employee { private String name; public Employee(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class ConstructorReferenceTest { public static void main(String[] args) { MyFunctionalInterface mf = Employee :: new; // constructor reference Function<String, Employee> f1 = Employee :: new; // using Function interface Function<String, Employee> f2 = (name) -> new Employee(name); // Lambda Expression System.out.println(mf.getEmployee("Raja").getName()); System.out.println(f1.apply("Adithya").getName()); System.out.println(f2.apply("Jaidev").getName()); } }
Output
Raja Adithya Jaidev
Advertisements