I have a functional Interface which contains 1 static method, 1 default method and 1 non-static abstract public method like below :-
package com.lambda;
@FunctionalInterface
public interface MyFunctionalInterface {
static void printDetails(){
System.out.println("Im a static method");
}
default void printDetails2(){
System.out.println("I'm in default method");
}
void printName();
}
From a different class, using Lambda expression, I'm trying to invoke and override these methods like below :-
package com.lambda;
public class Example1 {
public static void main(String[] args) {
//static method call
MyFunctionalInterface.printDetails();
//Lambda expression call to an abstract method
MyFunctionalInterface myFunctionalInterface = () -> System.out.println("My name is Vinod Kumar Nair");
myFunctionalInterface.printName();
//Lambda expression call to a default method
MyFunctionalInterface myFunctionalInterface1 = () -> System.out.println("Im overriding default method");
myFunctionalInterface1.printDetails2();
}
}
Here is the output, I'm getting :-
Im a static method
My name is Vinod Kumar Nair
I'm in default method
Using Lambda expression, I can invoke the static method called 'printDetails'. I can also override the 'printName()' with my implementation logic, where 'My name is Vinod Kumar Nair' is getting printed.
The problem is I'm not able to override the default method, printDetails2() with my implementation. I'm not getting the output as 'Im overriding default method'. I'm still getting the default implementation logic.
Is there any issue in overriding the default method using Lambda expression. If yes, then you can please tell me how to override this default method using the Lambda expression.
Thank you
@FunctionalInterface
means that you have only one method to implement.
When you do
MyFunctionalInterface myFunctionalInterface1 = () -> System.out.println("Im
overriding default method");
You implement the method, but not override any default method.
To override default methods you have to create a class which implements your interface and overrides the method there.
public class MyClass implements MyFunctionalInterface {
@Override
void printDetails2() { ... }
@Override
void printName() { ... }
}