I was exploring features of Java 8 and came across "Functional Interface".
As per my understanding, these interfaces can have some default implemented methods as :
@FunctionalInterface
public interface ComplexFunctionalInterface extends SimpleFuncInterface
{
default public void doSomeWork()
{
System.out.println("Doing some work in interface impl...");
}
default public void doSomeOtherWork()
{
System.out.println("Doing some other work in interface impl...");
}
}
But my doubt is, this what abstract class is for.
Why introduce functional interfaces.
But my doubt is, this what abstract class is for.
Why introduce functional interfaces.
Number of classes that can be extended: 1
Number of interfaces that can be implemented: more than 1
Functional interface are is used in a "safe" multiple inheritance. Differences:
Typical usage is when you want to embed default functionality into objects. I.e. if you have a function-like object,
class MyFunction1 {
public Integer apply(String s){
...
}
}
class MyFunction2 {
public List<String> apply(Integer s){
...
}
}
And you want to make a composition out of them, you just drop in implements Function
:
class MyFunction1 implements Function<String, Integer>{
public Integer apply(String s){
...
}
}
class MyFunction2 implements Function<Integer, List<String>>{
public List<String> apply(Integer s){
...
}
}
And you may create a composition of your functions. Two approaches compared:
No functional interfaces:
MyFunction1 myFunction1 = ...;
MyFunction2 myFunction2 = ...;
Function<String, List<String>> composition = (s) -> myFunction2.apply(myFunction1.apply(s));
With functional interfaces:
MyFunction1 myFunction1 = ...;
MyFunction2 myFunction2 = ...;
Function<String, List<String>> composition = myFunction1.andThen(myFunction2);
The difference
compose
and identity
.compose()
are not included into a class definition as it would result into class size growth. They are often put into separate utility classes. In Guava composition is put into a separate utility class Functions
: Functions.compose. So with new functional interfaces you would not need to recall in which utility class your function is implemented.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With