Java 8 New Features

Functional Interface

The definition of a functional interface is that it 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 represents that it can perform some behavior, but what specifically it does is determined by the caller through overriding this abstract method. This can be accomplished through 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 References

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

Function is also a type of functional interface that requires overriding its T apply(R) method.