Method and Constructor reference by using "::" operator
- The functional interface method can be mapped to our specified method by using "::" operator. This is called method reference.
- Our specified method can be either a static or instance method.
- The functional interface method and our specified method should have the same argument types except for return-type, method-name, modifiers, etc are not required to match.
Syntax
If our specified method is a static method.
Class-name::method-name
If the method is an instance method
Object-reference::method-name
Constructor references
We also can use ":: "operator to refer constructors
Syntax
Class-name::new
Example:
- class Student{
- private String name;
- Student(String name){
- this.name=name;
- }
- }
- interface A{
- public Student getName(String name);
- }
- class Test{
- public static void main(String[] args){
- A a= s-> new Sample(s);
- a.getName("Anu");
- A a1 = Student::new;
- a1.getName("Kalawati");
- }
- }
Note: In method and constructor references compulsory the argument types must be matched.