Java 8 — Method Reference | Code Factory
2 min readMay 8, 2020
Index Page : Link
Reference Link : Link
Donate : Link
Method Reference by Double Colon (::) Operator :
Method Calling by Lambda Reference :
package com.codeFactory.methodAndConstructorReference;interface Interf {
public void m1();
}public class Test {
public static void main(String... args) {
Interf i = () -> System.out.println("Lambda Expression");
i.m1();
}
}
Output :
Lambda Expression
Method Calling by :: Operator :
package com.codeFactory.methodAndConstructorReference;interface Interf {
public void m1();
}public class Test {
public static void main(String... args) {
Interf i = Test::m2;
i.m1();
}
public static void m2() {
System.out.println("Method Reference");
}
}
Output :
Method Reference
- Advantage of Method Reference is code reusability.
- Referer and Refering method both should have same argument type, return type can be different, modifier can be different and that method can be static or non-static.
- Method reference is alternative syntax to Lambda Expression.
- Function Interface can refer Lambda Expression, Functional Interface can refer method reference.
Syntax for Method Reference :
- Static method :
- classname :: method name
- e.g. Test::m2
- Instance method :
- object ref :: method name
- e.g. Test t = new Test(); ------> t::m2;
How many ways we can define a thread :
1. By extend thread class
2. By implementing runnable (3 ways)
2.1 Runnable r = new MyRunnable()
2.2 Runnable r = Lambda Expression
2.3 Runnable r = Method Reference
Thred using Lambda Expression :
package com.codeFactory.methodAndConstructorReference;public class Test {
public static void main(String... args) {
Runnable r = () -> {
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
}
};
Thread t = new Thread(r);
t.start();
for(int i=0; i<5; i++) {
System.out.println("Main Thread");
}
}
}
Output :
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Thread using Method Reference :
package com.codeFactory.methodAndConstructorReference;public class Test {
public void m1() {
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
}
}
public static void main(String... args) {
Test t = new Test();
Runnable r = t :: m1;
Thread t1 = new Thread(r);
//Thread t1 = new Thread(new Test()::m1);
t1.start();
for(int i=0; i<5; i++) {
System.out.println("Main Thread");
}
}
}
Output :
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread