What are functional interfaces used for in Java 8?

前端 未结 10 2112
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:59

    @FunctionalInterface annotation is useful for compilation time checking of your code. You cannot have more than one method besides static, default and abstract methods that override methods in Object in your @FunctionalInterface or any other interface used as a functional interface.

    But you can use lambdas without this annotation as well as you can override methods without @Override annotation.

    From docs

    a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere

    This can be used in lambda expression:

    public interface Foo {
      public void doSomething();
    }
    

    This cannot be used in lambda expression:

    public interface Foo {
      public void doSomething();
      public void doSomethingElse();
    }
    

    But this will give compilation error:

    @FunctionalInterface
    public interface Foo {
      public void doSomething();
      public void doSomethingElse();
    }
    

    Invalid '@FunctionalInterface' annotation; Foo is not a functional interface

提交回复
热议问题