What are functional interfaces used for in Java 8?

前端 未结 10 2241
Happy的楠姐
Happy的楠姐 2020-11-22 09:08

I came across a new term in Java 8: "functional interface". I could only find one use of it while working with lambda expressions.

Java 8 provides

10条回答
  •  遥遥无期
    2020-11-22 09:54

    Functional Interface:

    • Introduced in Java 8
    • Interface that contains a "single abstract" method.

    Example 1:

       interface CalcArea {   // --functional interface
            double calcArea(double rad);
        }           
    

    Example 2:

    interface CalcGeometry { // --functional interface
        double calcArea(double rad);
        default double calcPeri(double rad) {
            return 0.0;
        }
    }       
    

    Example 3:

    interface CalcGeometry {  // -- not functional interface
        double calcArea(double rad);
        double calcPeri(double rad);
    }   
    

    Java8 annotation -- @FunctionalInterface

    • Annotation check that interface contains only one abstract method. If not, raise error.
    • Even though @FunctionalInterface missing, it is still functional interface (if having single abstract method). The annotation helps avoid mistakes.
    • Functional interface may have additional static & default methods.
    • e.g. Iterable<>, Comparable<>, Comparator<>.

    Applications of Functional Interface:

    • Method references
    • Lambda Expression
    • Constructor references

    To learn functional interfaces, learn first default methods in interface, and after learning functional interface, it will be easy to you to understand method reference and lambda expression

提交回复
热议问题