What are functional interfaces used for in Java 8?

前端 未结 10 2359
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 10:04

    An interface with only one abstract method is called Functional Interface. It is not mandatory to use @FunctionalInterface, but it’s best practice to use it with functional interfaces to avoid addition of extra methods accidentally. If the interface is annotated with @FunctionalInterface annotation and we try to have more than one abstract method, it throws compiler error.

    package com.akhi;
        @FunctionalInterface
        public interface FucnctionalDemo {
    
          void letsDoSomething();
          //void letsGo();      //invalid because another abstract method does not allow
          public String toString();    // valid because toString from Object 
          public boolean equals(Object o); //valid
    
          public static int sum(int a,int b)   // valid because method static
            {   
                return a+b;
            }
            public default int sub(int a,int b)   //valid because method default
            {
                return a-b;
            }
        }
    

提交回复
热议问题