Saturday, June 14, 2014

Java 8 : Frequently Asked Questions for Interviews - 5


What are Functional Interfaces

A functional interface is an interface with a single abstract method. That abstract method is used as the type of a lambda expression.
public interface ActionListner extends EventListener {
      public void actionPerformed( ActionEvent event);
}
In the above example ActionListener has only one method actionPerformed and we use it to represent the action that takes one argument and returns no result. => It is a functional Interfaces.
  • It doesn't matter what the single method ( e.g. actionPerformed ) is called. 
  • The method will match up to lambda expression as long as it has compatible method signature
  • One can see the type of the parameter in the functional interface => improves readability and understanding in code.
  • Functional interfaces can use generics also.
  • Some important functional interfaces in Java :
Interface NameArgumentsReturnsExample
Predicate<T>sasdadasTdfasdfasdfafsadfsbooleanasfsdfsdadfsdHas this book been published yet?aasdfsdfasdfasdfasdfasdfasdfasfsdfsfsdfsdadfsd
Consumer<T>TvoidPrinting out a value. Getting an action/task done.
Function<T,R>TRGet a property/instance var from an object. Eg: get the author from book object
Supplier<T>NoneTAny Factory Method. Get Constant Values defined in certain context.
UnaryOperator<T>TTLogical not (!)
BinaryOperator<T> (T,T)(T,T)TMultiplying two numbers (*)

  • There are many interfaces in Java that encapsulates blocks of code such as "Runnable" or "Comparator"
  • Lambdas are backwards compatible with these interfaces.

When to supply Lambda Expression?

  • When an object of an interfaces with a single method is expected. Eg. ActionListerner is the functional interfaces in  the following example: The Left Hand Side Code changes to written in Lambda expression in the right hand side.
  • button.addActionListener( new ActionListener() {

        public void actionPerformed(ActionEvent event){
            System.out.println("Click on Button");
            }
    })
    button.addActionListerner( event ->
                 System.out.println("Click on Button"); )
  • The boiler plate code is minimized, readability enhanced and meaningfulness accomplished.

Why a functional interface must have a single abstract method. Aren’t all methods in an interface abstract?

  • In Java 8, interfaces can declare nonabstract methods.
  • Some interfaces in the Java API redeclare Objectmethods (such as toString or clone) to attach javadoc comments. But these declarations do not make the methods abstract.
    • Check out the Comparator API for an example.

No comments:

Post a Comment