java lambda method and new Object

  • A+
Category:Languages

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();//from this method  not do everyThing         System.out.println(runnable);         Runnable demo = new Demo(); //using new to create method         demo.run();         System.out.println(demo);     } } 

which prints

  1. RefDemo$Demo@7291c18f----- //lambda run constructor methods print
  2. RefDemo$$Lambda$1/793589513@34a245ab //main method print
  3. RefDemo$Demo@7cc355be-----
  4. run
  5. RefDemo$Demo@7cc355be

I don't know why the code does not print run when calling runnable.run();. Can you tell me why that happens?


You are simply using Runnable in too many places and confusing yourself. The following code makes it a bit clearer what is happening:

public class RefDemo {      static class Demo {          public Demo() {             System.out.println(this.toString() + "-----");         }          public void something() {             System.out.println("something");         }     }      public static void main(String[] args) {         Runnable runnable = Demo::new;          runnable.run();          System.out.println(runnable);          Demo demo = new Demo();         demo.something();          System.out.println(demo);     } } 

Runnable runnable = Demo::new; means that you now have a reference to the constructor of Demo (which still works after dropping the conformance to the Runnable interface). And you store that reference in a variable of type Runnable which only works because their functional interfaces are compatible. Calling run on that reference then simply calls the constructor, not the run / something method of Demo.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: