Why doesn't the first of the following examples work?
run(R::new);methodR.runis not called.run(new R());methodR.runis 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 newRunnablewhich does nothing1.By
new R(), you create an instance of theRclass where therunmethod is well-defined.1 Actually, it creates an object of
Rwhich has no impact on execution.I was thinking of treating 2 invocations identically without modifying the
mainmethod. We would need to overloadrun(Runnable)withrun(Supplier<Runnable>).