Can @FunctionalInterfaces have default methods?

前端 未结 4 1415
天命终不由人
天命终不由人 2021-01-01 08:59

Why can\'t I create a @FunctionalInterface with a default method implementation?

@FunctionalInterface
public interface MyInterface {
    default         


        
4条回答
  •  死守一世寂寞
    2021-01-01 09:35

    A functional interface is an interface having a single abstract method. The entire purpose of defining functional interfaces is to enable the implementation of the single abstract method via lambda expressions which will effectively override that method which makes providing a default implementation for it pointless.

    Having an interface consisting entirely of default methods raises multiple problems. There is the technical problem that the compiler can’t decide for a lambda expression which method to implement when there are multiple default methods and there is the semantic problem that an interface consisting entirely of default methods is not abstract. You can’t instantiate this default behavior as you can’t instantiate interfaces and are forcing programmers to create concrete classes just to invoke the default behavior, which, since interfaces are stateless, could be provided by a singleton instead:

    @FunctionalInterface
    public interface MyInterface {
        static MyInterface DEFAULT = s->true;
        boolean authorize(String value);
    }
    

    Note that you can have interfaces extending a functional interface and providing a default method, if you need. Still, if this results in creating an interface having no abstract methods I would question the design. You may compare with the discussion about marker interfaces with default methods. If the sub-interface will have different abstract methods than the functional interface, it’s a different story. There might be real use cases for this, but these sub-interfaces will also demonstrate why they shouldn’t be mixed with the functional base interface as a lambda expression will always implement the abstract method.

提交回复
热议问题