2020-03-04

Java Functional interfaces

Functional interfaces

If an interface only has one abstract method (aside from methods of Object), it’s called functional interface. Functional interfaces are special because instances of functional interfaces can be created with lambda expressions or method references.

If an interface is designed to be functional, it should be marked with @FunctionalInterface annotation. Compiler will generate an error if the interface doesn’t meet the requirements of being a functional interface.


There are already several functional interfaces, e.g.
• java.lang.Runnable
• java.util.concurrent.Callable
• java.util.Comparator
• java.io.FileFilter

Java SE 8 adds a new package java.util.function which includes new functional interfaces.

Functional interfaces and single responsibility principle 
"Single responsibility principle" states that every class should only have one responsibility and only one reason to change. Functional interfaces only provide one abstract method to implement, which makes functional interfaces the nature choice to apply single responsibility principle. With the power of lambda expressions, implementing function interfaces is also very elegant. Using functional interfaces is a good combination of design principle and coding practice. When writing your own application, try to always use functional interfaces. This can also help to create better design. http://en.wikipedia.org/wiki/Single_responsibility_principle

No comments:

Post a Comment