I just started learning java8 stream api. I have seen a method which has input type Runnable
interface even it's allow to pass this::greet
as param. when program is run, why does this not call greet method? its output only Hello, world!2
. why does it allow to pass such method even input is runnable interface?
public class TestAnno {
public static void main(String[] args) {
TestAnno anno=new TestAnno();
}
public TestAnno() {
display(this::greet); // what is use of calling this method
display(this.greet()); //compiler error: The method display(Runnable) in the type TestAnno is not applicable for the arguments (void)
}
private void display(Runnable s) {
System.out.println("Hello, world!2");
//Arrays.sort(new String[]{"1","2"}, String::compareToIgnoreCase);
}
public void greet() {
System.out.println("Hello, world! greet");
}
}
I have created interface to understand it.
public interface Inter1 {
void hello();
void hello1(int a);
}
Now I change display method param to Inter1
instead of Runnable
. it throw error 'The target type of this expression must be a functional interface'.
like
public class TestAnno {
public static void main(String[] args) {
TestAnno anno=new TestAnno();
}
public TestAnno() {
display(this::greet); // The method display(Inter1) in the type TestAnno is not applicable for the arguments (this::greet)
display(()->this.greet());//The target type of this expression must be a functional interface
}
/*private void display(Runnable s) {
System.out.println("Hello, world!2");
Arrays.sort(new String[]{"1","2"}, String::compareToIgnoreCase);
}*/
private void display(Inter1 s){
}
public void greet() {
System.out.println("Hello, world! greet");
}
}
Can any one help on this!!