Search code examples
javainterfacefunctional-programmingabstractfunctional-interface

Can we use lambda expression inside an interface as a default or static implementation inside interfaces?


I have this strange doubt now, As far as I know, in order to use lambda expressions it should be a functional interface having single abstract method. Now the question is can we provide its implementation in another interface as a static or default implementations? Thank you.


Solution

  • You can define a lambda expression that would represent an A instance regardless of the context you are in. It can be a static interface method, it could be a default interface method.

    @FunctionalInterface
    interface A {
        void printMessage();
    }
    interface B {
        default void printMessage() {
            A a = () -> System.out.println("A implementation (1)");
            a.printMessage();
        }
    }
    interface C {
        static void printMessage() {
            A a = () -> System.out.println("A implementation (2)");
            a.printMessage();
        }
    }
    

    As you may have noticed, it's not particularly useful because both methods could be simply rewritten to

    System.out.println("...");
    

    If there is a relationship between interfaces, a default method would provide an implementation for the method defined in the super interface. A static method would cause a compilation error since they can't override instance methods.

    @FunctionalInterface
    interface A {
        void printMessage();
    }
    interface B extends A {
        @Override
        default void printMessage() {
            A a = () -> System.out.println("A implementation (1)");
            a.printMessage();
        }
    }
    interface C extends A {
        // compilation error
        static void printMessage() {
            A a = () -> System.out.println("A implementation (2)");
            a.printMessage();
        }
    }