Override the default method using lambdas

Given a simple interface with a standard method:

private interface A { default void hello() { System.out.println("A"); } } 

And the method that takes its instance:

 private static void print(A a) { a.hello(); } 

I can override this with an anonymous class:

 print(new A() { @Override public void hello() { System.out.println("OverHello"); } }); 

but if I try to use lambda print(() -> System.out.println("OverHello2")); I get a compilation error.

No target method found

Is there a way to do an override with lambda?

+6
source share
2 answers

No, because your interface does not have exactly one unrealized method (which lambda can provide an implementation for).

See @FunctionalInterface .

+7
source

Lambdas does not allow overriding default methods. This was a deliberate design choice, as it allows the use of functional interfaces (interfaces that can be created via lambda) to have one or more default methods.

To successfully enable creation of A via lambda, you cannot define a default for hello() .

0
source

All Articles