Computing Magazine

Double Colon Operator in Java

Posted on the 06 August 2015 by Abhishek Somani @somaniabhi

Java 8 has introduced double colon (::) apart from lambda expressions. Let's see how does it work .

public class DoubleColonTest {
  
  interface MyInterface{
      public void interfaceMethod(String input);
  }
  
  public static void staticmethod(String input)
  {
    System.out.println(" static mymethod  " + input);
  }
  
  public void method1(String input)
  {
    System.out.println(" mymethod  " + input);
  }
  
  public static void main(String[] args) {
    DoubleColonTest obj = new DoubleColonTest();
    MyInterface dd = obj::method1;
    dd.interfaceMethod(" test string ");
    MyInterface second = DoubleColonTest::staticmethod;
    second.interfaceMethod(" test static string ");
      
    
  }

}

In this example , we have a functional interface with method name interfaceMethod , and we have a DoubleColonTest class which has two method which takes same parameters as interfaceMethod .Now this line :

MyInterface dd = obj::method1;

This line tells the compiler to create an implementation of MyInterface by applying the body of method1 defined in the DoubleColonTest class . Since this method is instance method , we need to use instance of class. This is called instance method reference .We can take static method reference also like this :

MyInterface second = DoubleColonTest::staticmethod;

So , now we can reference methods and reuse them again and again . We can also reference Constructor also , but we need to have a constructor which matches the interface method signature like this :

public DoubleColonTest(String in)
  {
    System.out.println(" constructor  " + in);
  }

Now to create an implementation of MyInterface , just need to write :

 MyInterface third = DoubleColonTest::new;
 third.interfaceMethod(" test string ");

please post comments and suggestions !!!

Double Colon Operator in Java


Back to Featured Articles on Logo Paperblog