Functional Interface in Java 8


The functional interface can have only ONE abstract method. If you have two abstract methods then your interface is no longer functional.

If you have one abstract method you can use lambda expressions.

If you see the @FunctionalInterface annotation you know that you shouldn't add any new methods, because it will break design.

If you add new abstract method to any java interface it will break code anyway, because you 

need to provide implementation to concrete classes.

Following  example  we can calculate    value  using  functional  interface 



 @java.lang.FunctionalInterface

interface Calculator{

public abstract int  calculate(int a, int b);

static void  myStatic() {

 System.out.println("This is static method in  functional interface ");

}


public  default  void  mydefault() {

  System.out.println("This is default method in  functional   interface ");

}

 

}




public  class FunctionalInterface implements  Calculator    {

 

public  int  calculate(int a, int b) {

return   a/b ;

}


public static void main(String[] args) {

// TODO Auto-generated method stub


Calculator  c= (int x , int y)-> x*y ; 

Calculator    c1=(int x , int y)->x+y;

           

Calculator    c2=(int x , int y)->x-y;

             

             

            int  multiply=c.calculate(15, 4);

             

            int  add=c1.calculate(15, 4);

            int  sub=c2.calculate(15, 4);

     System.out.println(  "Multiply:"+multiply);

        System.out.println("Add:"+add);

        System.out.println("Sub:"+sub);

       

      Calculator  ct=new FunctionalInterface();

       

 System.out.println("D:" +ct.calculate(50, 10));


           

   ct.mydefault(); //  default  method  print 

           

    Calculator.myStatic();//Static method call


        }





     }








Program Output:


Multiply:60

Add:19

Sub:11

D:5

This is default method in  functional   interface 

This is static method in  functional   interface 

Functional Interface in Java 8  Functional  Interface  in Java 8 Reviewed by Mukesh Jha on 9:48 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.