Java 8 - Method Reference By using :: (Double Colon) Operator

Method Reference By using :: (Double Colon) Operator:

* Instead of Lambda Expression we can go for Method Reference.
* We are not required to provide any new implementation, just we want to refer another method.
* It is used for Code reusability. - Benefit

Rule:
* Both methods should have same argument types.
* See Below example in m1() & m2()

Eg.
interface Interf{
public void m1();
}

Static method example:
Syntax: 
Classname::methodName
Example Program:
Class Test{
public static void m2(){
System.out.println("method reference");
}
public static void main(String args[]){
Interf i = Test::m2;
i.m1();
}
}
// M1 want to refer M2(Static method)

Instance method example:
Syntax:
ObjectReference::methodName
Example Program:
Class Test{
public static void m2(){
System.out.println("method reference");
}
public static void main(String args[]){
Test t = new Test();
Interf i = t::m2;
i.m1();
}
}

Lambda vs Method Reference Program:
with Lambda:
Class Test{
public static void main(String args[]){
Runnable r = () -> {
for(int i=0;i<10;i++){
System.out.println("child thread");
}
};
Thread t = new Thread(r);
t.start();
for(int i=0;i<10;i++){
System.out.println("Parent thread");
}
}
}
With Method Reference:

Class Test{
public void m1(){
for(int i=0;i<10;i++){
System.out.println("child thread");
}
}
public static void main(String args[]){
Test t = new Test();
Runnable r = t ::m1();
Thread t = new Thread(r);
t.start();
for(int i=0;i<10;i++){
System.out.println("Parent thread");
}
}

}

Comments

Popular posts from this blog

How to set Java Object into JaxBElement ?

GitLab