javainterfacemethod-referencesupplier

Supplier interface for constructor reference


the following code

Supplier<String> newString = String::new;
System.out.println(newString.get());
// prints an empty string (nothing) to the console and then a newline character

and for the definition of Supplier get method

T get()

the get method should return T, but constructor has no return type, so why String::new can be assigned to Supplier <String>?


Solution

  • calling a constructor (new) creates an object and "returns" it, as you see.

    Object object = new Object();
    

    ā†’ if a constructor would not return anything, this code was false...

    But it isn't.

    Therefore, the following example is okay

    new Thread(new Runnable() {
      @Override public void run() {
        System.out.print("it runs.");
      }
    }).start();