//Base Interface - Functional Interface as it contains only one abstract method
@FunctionalInterface
public interface BaseInterface {
int sum(int a, int b);
}
Instantiating the functional interface using lambda expression
public class Implementer {
public static void main(String[] args) {
BaseInterface base = (num1, num2) -> num1 + num2;
System.out.println(base.sum(3, 2));
}
}
Functionality extended in interface - new default method is added
@FunctionalInterface
public interface BaseInterface {
int sum(int a, int b);
default String getUserDetails(String name) {
return name;
}
}
If I override the default method to have specific implementation rather than the default one - have to use 'implements' keyword for specifying the interface this way:
public class Implementer implements BaseInterface {
public String getUserDetails(String uname) {
uname = uname.trim();
return uname;
}
public static void main(String[] args) {
BaseInterface base = (num1, num2) -> num1 + num2;
System.out.println(base.sum(3, 2));
}
}
In this case, the compiler throws an error and prompts to implement the inherited abstract methods. So, should I have to implement the abstract methods the usual way in this case
public class Implementer implements BaseInterface {
public String getUserDetails(String uname) {
uname = uname.trim();
return uname;
}
public static void main(String[] args) {
//BaseInterface base = (num1, num2) -> num1 + num2;
System.out.println(base.sum(3, 2));
}
@Override
public int sum(int a, int b) {
return a + b;
}
}
(or) is there a way to still use the lambda expression?
Implementeris declared as anabstractclass?Implementerclass abstract you don't implement thesummethod, that's why the class is still abstract. Anyway, it's absolutely OK to have an abstract class without abstract methods. An abstract class represents something you cannot instantiate, but it doesn't need to contain abstract methods.