Table of content

:: Double Colon Operator

:: Double Colon Operator is introduced in Java 1.8, it is used to provide a method reference. We can call a method if we have a reference, which means we do call the method immediately, but we will call the method later.

Method will not be invoked when referenced

Method reference is one of the features belonging to Java lambda expressions. A method reference can be expressed using the usual lambda expression syntax format using –>. To make it more simple :: operator can be used.

Functional Interface:

An Interface containing only one method is known as a Functional interface. Below example shows the ICalculate interface has only one method called add().

interface ICalculate{
	void add();
}

Few other functional interfaces are, Comparable, Runnable, and AutoCloseable are some functional interfaces in Java.

By default, all the abstract methods in the Interface are public.

Lambda style of calling an interface method:

We can provide implementation to an abstract method using the lambda expression in java.

public class DateTimeExample {
	public static void main(String[] args) {
		ICalculate ic = () ->{
			System.out.println("Addition method");
		};
		ic.add();
	}
}
interface ICalculate{
	void add();
}

double-colon-method

:: Double Colon Operator

:: operator helps the user to provide a reference to the method as an override to the abstract method in the interface. The referenced method will be invoked whenever there is a call to the method present in the Interface.

We can provide a reference to the existing methods only. In the below program, We have an Interface called ICalculate and contains add() method as an abstract method. The class DateTimeExample has a method called sum().

Inside the main method, I have provided the reference to the m2 method using :: operator. So if I call the abstract method present in the Interface then sum() method will be invoked

public class DateTimeExample {
	public static void main(String[] args) {
		ICalculate ic = DateTimeExample::sum;
		ic.add();
	}
	public static void sum(){
		System.out.println("This is sum method");
	}
}
interface ICalculate{
	void add();
}

double-colon-method

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions