How the functional interface working in java 8

mallikarjun :

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)

MC Emperor :

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

  • the target type is the functional interface Sayable (you're trying to store the result into a Sayable type); and
  • the signature of the method reference to saySomething() 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97485&siteId=1