-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodReference.java
More file actions
45 lines (39 loc) · 1.22 KB
/
MethodReference.java
File metadata and controls
45 lines (39 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package Lambda;
interface LambdaMeth{
void display(String s);
}
interface LambdaMeth2{
int compare(String s1, String s2);
}
class DemoClass{
DemoClass(){
System.out.println("I'm Constructor");
}
static void reverse(String s){
StringBuffer sb = new StringBuffer(s);
sb.reverse();
System.out.println("Reverse: "+sb);
}
void getLength(String s){
StringBuffer sb = new StringBuffer(s);
System.out.println("Length: "+sb.length());
}
}
public class MethodReference {
public static void main(String[] args) {
//Overwrites display method by println
LambdaMeth lm = System.out::println;
lm.display("Method Reference for static methods");
//Overwrites display method by reverse
lm = DemoClass::reverse;
lm.display("ytrewq");
//Overwrites display method by getLength
DemoClass mr = new DemoClass();
LambdaMeth lml = mr::getLength;
lml.display("qwertyuiopasdfghjklzxcvbnm");
//using pre-defined method for overwriting display method
LambdaMeth2 jk = String::compareTo;
System.out.println("Compare: "+jk.compare("a","A"));
}
}
// It is much like polymorphism mechanism