Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Method references default method implementation

Tags:

java

 interface HelloWorld {
    String hello(String s);
}
public static void main(String[] args) {
        HelloWorld h = String::new;
        System.out.println(h.hello("dasdasdadasd"));
}

When I execute the above method,it returns the value which I am passing in the arguments dasdasdadasd Which method of string class is executed or is there any default implementation which java provides at runtime or by default it calls supplier.get() method?

like image 710
Prasad Avatar asked Nov 30 '25 23:11

Prasad


2 Answers

h was assigned a method reference to the public String(String original) constructor of the String class. That's the only constructor that matches the signature of the String hello(String s) method of your HelloWorld interface.

Therefore h.hello("dasdasdadasd") creates a new String instance whose value is equal to "dasdasdadasd" and returns that instance.

HelloWorld h = String::new;

is equivalent to:

HelloWorld h = s -> new String(s);
like image 107
Eran Avatar answered Dec 03 '25 12:12

Eran


Your code can be rewritten as:

hw returns a string created from what it receives:

//Returns a string based on the input
HelloWorld hw = (s) -> {
    return new String(s);
}; 

Invoking hello() on that object returns "basically" the input:

//The value assigned to print is "dasdasdadasd", as returned by hw
String print = hw.hello("dasdasdadasd");

println Is receiving dasdasdadasd:

System.out.println(print); //"dasdasdadasd" is passed to println
like image 25
ernest_k Avatar answered Dec 03 '25 14:12

ernest_k