Pages

Saturday 21 September 2019

Double colon operator


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:

  1. class Student{
  2. private String name;
  3. Student(String name){
  4. this.name=name;
  5. }
  6. }
  7. interface A{
  8. public Student getName(String name);
  9. }
  10. class Test{
  11. public static void main(String[] args){
  12. A a= s-> new Sample(s);
  13. a.getName("Anu");
  14. A a1 = Student::new;
  15. a1.getName("Kalawati");
  16. }
  17. }
Note: In method and constructor references compulsory the argument types must be matched.