I have the following code:
public class RefDemo {
static class Demo implements Runnable {
public Demo() {
System.out.println(this.toString() + "-----");
}
@Override
public void run() {
System.out.println("run");
}
}
public static void main(String[] args) {
Runnable runnable = Demo::new; // lambda ref constructor method
runnable.run(); // does not do anything
System.out.println(runnable);
Runnable demo = new Demo(); // using new to create a Demo instance
demo.run();
System.out.println(demo);
}
}
Which prints:
RefDemo$Demo@7291c18f----- // lambda run constructor method print
RefDemo$$Lambda$1/793589513@34a245ab // main method print
RefDemo$Demo@7cc355be-----
run
RefDemo$Demo@7cc355be
I don't know why the code does not print run when calling runnable.run();
Why does that happen?
runnable.run()calls the constructor, not therunmethod ofDemo.new Demo()andDemo::neware not equivalent.runnable.run().run()