Methods Expressions

Method reference is a way in lambda expression to refer a method without executing it. In body of lambda we can call another methods if they are compatible with functional interface.

When method reference is evaluated then instance of functional interface created.


Method reference to Static methods

Static method can be referred by using class name. In lambda expression to refer static method following syntax is used.

Syntax:


 Class-name::Method-name;
   

"::" operator is introduced in jdk8 for this purpose only. "::" operator is used to separate class name from method name.

Let's take one example



//Functional Interface 
interface one
{
void func();
}


// Normal class having static method.
class three
{ static void msg()
{
System.out.println("Hello world");
}
}
class two
{
public static void main(String arg[])
{
//reference of functional interface.
one o;

// defining functionality of method func();
// Using method reference
// Now calling of func() method will refer msg() method of class three.
o=three::msg;

//Calling of func() method.
o.func();
}
}

/*Output:
Hello world
*/

Above example demonstrating how a static method can be assigned to functional interface. This assignment of functionality to functional interface is done by using Method reference.



Method reference to Instance method

Instance method also can be referred by lambda expression. For referring instance method it need instance-name instead of class-name. "::" operator is used to refer instance method also.


Syntax:


Instance-name::Method-name;
   

Let's take above example with instance method msg()


 
//Functional Interface
interface one
{
void func();
}

// Normal class having a instance method.
class three
{
void msg()
{
System.out.println("Hello world");
}
}


class two
{
public static void main(String arg[])
{
// Creating instance of class three
three ob1=new three();

//reference of functional interface.
one o;

// defining functionality of method func();
// Using method reference
// Now calling of func() method will refer msg() method of class three.
o=ob1::msg;

//Calling of func() method.
o.func();
}
}

/*Output:
Hello world
*/

In above program there is a method in class three. This method is instance method. So in order to refer this method instance of class three is needed. Instance method msg() is referred by using instance name.