Here is an example I ran across while studying the functional interface concept.
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
This is printing "Hello, this is static method." in output when it runs. My question how it is printing the output when we call the say() method( which is not implemented)
You can think of the method reference like this:
Sayable sayable = new Sayable() {
@Override
void say() {
// Grab the body of the method referenced by the method reference,
// which is the following:
System.out.println("Hello, this is static method.");
}
}
The method reference is valid because
Sayable
(you're trying to store the result into a Sayable
type); andsaySomething()
matches the functional interface method say()
, that is, the parameters and the return type match1.The implementation of the say()
method of the Sayable
instance referred to as the variable sayable
equals the body of the method the method reference refers to.
So like JB Nizet says in the comments, say()
actually is implemented.
1 A little detail: the word 'match' does not exactly mean 'are equal'. E.g. if saySomething()
returned an int
, it would still work, although the target type's only method defines the return type to be void
.