Consider below code,
class DemoStatic {
public static Runnable testStatic() {
return () -> {
System.out.println("Run");
};
}
public void runTest () {
Runnable r = DemoStatic::testStatic;
r.run();
}
}
public class MethodReferenceDemo {
public static void main(String[] args) {
DemoStatic demo = new DemoStatic();
demo.runTest();
}
}
run()
method of Runnable
instance that is being return by testStatic
method was supposed to be invoked.
And output on console should be "Run".
But this code is not invoking run()
method of instance r
and nothing is getting printed in console.
Can some one please explain the reason.
And comment if I am not using Method reference "::" properly.
To expand a bit on Sotirios' answer:
This statement:
is equivalent to
So
r.run()
calls a method that callstestStatic()
to return a newRunnable
, but then does nothing with it.This
returns a
Runnable
whoserun()
method contains the body of the methodtestStatic()
, ie.so
basically executes
dropping the
return
value.It's a
static
method reference. A method reference meaning yourRunnable
is referencing and executing the method in the method that functional interface defines.For the behavior you want, you have to do