New Features in Java 8

Functional Interface

A functional interface is defined as an interface that must contain only one abstract method. It can have many static or default methods (with implementations), but there must be only one abstract method.

This abstract method indicates that it can perform a certain behavior, but the specific action is determined by the caller through overriding this abstract method. This can be achieved using anonymous inner classes or lambda expressions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void main(String[] args) {
    // Anonymous inner class
    FunctionalInterface functionalInterface = new FunctionalInterface() {
        @Override
        public void execute() {
            System.out.println("Executing functionalInterface");
        }
    };
    functionalInterface.execute();
    // Lambda expression
    FunctionalInterface functionalInterface1 = ()-> System.out.println("Executing functionalInterface1");
    functionalInterface1.execute();
}

Method Reference

1
2
3
4
// Lambda
Function<String, Integer> function=(string)->string.length();
// Method reference
Function<String, Integer> function1= String::length;

Function is also a functional interface, requiring its T apply(R) method to be overridden.