Learn to create generic functional interfaces with and without type restrictions in Java 8 and later. Note that functional interfaces permit exactly one abstract method. These interfaces are also called Single Abstract Method interfaces (SAM Interfaces).
1. Without Type Restrictions
1.1. Interface Definition
A functional interface can be defined that is generic for type X
and has a functional method that accepts two arguments of type X
and returns a value of type X
.
This interface can be used for any type i.e. ArgumentsProcessor<Integer>
, ArgumentsProcessor<String>
or ArgumentsProcessor<Employee>
.
1.2. Example
Java example to use generic functional interface with type Integer
.
Java example to use generic functional interface with type String
.
2. With Type Restrictions
2.1. Interface Definition
A functional interface can be defined that is restricted to certain types using extends
keyword i.e. X extends Number
.
This interface can be used for any type i.e. ArgumentsProcessor<Integer>
, ArgumentsProcessor<Double>
but not for ArgumentsProcessor<String>
or ArgumentsProcessor<Employee>
.
In the above example, the permitted type must extend the Number
class.
2.2. Example
Java example to use generic functional interface with type Integer
.
3. Specialized Functional Interfaces
Specialization is accomplished by extending or implementing the generic functional interface of one type. The resulting interface or class is not generic for that type.
Drop me your questions related to functional interfaces with generics.
Happy Learning !!
Comments