Why doesn't the first of the following examples work?
run(R::new);
methodR.run
is not called.run(new R());
methodR.run
is called.
Both examples are compiled-able.
public class ConstructorRefVsNew {
public static void main(String[] args) {
new ConstructorRefVsNew().run(R::new);
System.out.println("-----------------------");
new ConstructorRefVsNew().run(new R());
}
void run(Runnable r) {
r.run();
}
static class R implements Runnable {
R() {
System.out.println("R constructor runs");
}
@Override
public void run() {
System.out.println("R.run runs");
}
}
}
The output is:
R constructor runs
-----------------------
R constructor runs
R.run runs
In the first example, the R
constructor is called, it returns lambda (which is not object):
But then how is it possible, that the example is compiled successfully?
Compare two calls:
By
((Runnable)() -> new R())
or((Runnable) R::new)
, you create a newRunnable
which does nothing1.By
new R()
, you create an instance of theR
class where therun
method is well-defined.1 Actually, it creates an object of
R
which has no impact on execution.I was thinking of treating 2 invocations identically without modifying the
main
method. We would need to overloadrun(Runnable)
withrun(Supplier<Runnable>)
.