Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a default method using lambdas

Tags:

java

lambda

Given a simple interface with a default method:

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

And a method that accepts an instance of it:

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

I can override this using an anonymous class:

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

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

No target method found

Is there a way to make the override with a lambda?

like image 682
T4l0n Avatar asked Jan 20 '16 15:01

T4l0n


People also ask

Can you override a default method?

A class can override a default interface method and call the original method by using super , keeping it nicely in line with calling a super method from an extended class. But there is one catch, you need to put the name of the interface before calling super this is necessary even if only one interface is added.

How do you call a default method using lambda expression?

Default methods can be used in lambda expressions. Formula formula = (a) -> sqrt( a * 100); is to define a Formula , which works as functional interface, directly via a lambda expression. Formula formula = (a) -> sqrt( a * 100);

Can I override default method in functional interface?

It is not mandatory to override the default method in Java. If we are using Only one interface in a Program then at a time we are using only a single default method and at that time Overriding is not required as shown in the below program: Java.

Can we override lambda expression in Java?

lambdas are the implementation of a Functional Interface, not abstract classes. Therefore, you can't do this with your SimpleFileVisitor .


1 Answers

No, because your interface does not have exactly one unimplemented method (that a lambda could provide the implementation for).

See @FunctionalInterface.

like image 155
Bohemian Avatar answered Oct 10 '22 22:10

Bohemian