Functional interface in Java

Quick example

/**
 * Declare our functional interface
 */
@FunctionalInterface
public interface CustomLogger {
    public void log(String message);
}

class Demo {
    public static String message = "Hello World!";

    public static logMessage(CustomLogger customLogger) {
        customLogger.log(message);
    }
}

Demo.logMessage(message -> {
    System.out.println(message);
});

/*
If this wasn't a functional interface then in that case
we would have required to create a class that implements
CustomLogger, then override log method and 
then pass a new instance of it to logMessage
*/

Leave a Reply

Your email address will not be published. Required fields are marked *