Method Referencing in Java 8 or Above
Method References
The mapping of Function Interface method to the specified method by using “::” (double colon) operator is called Method Referencing. This specified method can be either a static or instance method. But there is a condition, Functions Interface method and specified method should have same argument types, except this the remaining things like return type, method name, access modifier is not required to match.
The syntax for Method References:
A) If a specified method is a static method:
Classname::methodName
B) If a specified method is an instance method:
Objectname::methodName
Let’s understand with an example:
@FunctionalInterface
interface Message
{
public abstract void msg();
}
class DisplayMessage
{
public void display()
{
System.out.println(“This is method references example”);
}
public static void display2()
{
System.out.println(“This is method references example”);
}
}
public class Test
{
public static void main (String [] args)
{
DisplayMessage dm = new DisplayMessage();
Message m1 =dm::display();
m1.msg();
Message m2 =DisplayMessage::display2();
m2.msg();
}
}
Constructor References
The mapping of the constructor to the specified method by using “::” (double colon) operator is called Constructor Referencing.
The syntax for Constructor References:
Classname::new
Let’s understand with an example:
@FunctionalInterface
interface Message
{
public abstract void msg ();
}
class DisplayMessage
{
public DisplayMessage()
{
System.out.println(“This is method references example”);
}
}
public class Test
{
public static void main (String [] args)
{
Message m1 =DisplayMessage::new;
m1.msg();
}
}