Interface In Java 8

Interface :

It is similar to a class in java, instead, with a keyword as interface. 
Interface used as method declaration, not for implementation untill jdk7

Eg:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
Public interface MyInteface {
 Void m1(String str);
 Void m2(int i);

 // But you cannot write as follows in interface
 /*Void m3(String s){
 System.out.println("You cannot write this way. "); 
     }*/

}




Interface in Java-8 :

Java-8 interface can have STATIC DEFAULT methods, we can also have method implementation from jdk 8 but has to be default

Eg: Before JAVA-8 

1
2
3
4
5
6
7
Public interface MyInterface{
     Void m1(String str);
     /* Default void m2(String str){
          System.out.println(“Gives an error in prior jav-8 versions. ”);
    } //Gives you an error
  
  */
}



Code In Java-8

Java-8 Functional Interface

Java Functional Interface



If look into some other programming languages like c++, Javascript they are called functional programming languages bcoz, we can write functional and use whenever required.

An interface with only 1 abstract method is called Functional interface.
A new annotation @FunctionalInteface provides us to avoid accidental addition od abstract methods.
Functional interface is long waited and much sought out feature of Java-8 as it enables us to use Lambda expressions to instantiate them.

Being object-oriented is not bad, but when we wanted to implement Runnable we do it as follows

Eg: 


1
2
3
4
5
Runnable r = new Runnable(){
   @Override
   public void run() {
    System.out.println("My Runnable");
   }};

If you notice it, the important logic in under run() method right?

Java-8 lambda expressions allow to help us in writing smaller and cleaner code.


Lambda Expressions:

Lambda expression is way through we can visualize functional programming in java object world.
Objects are base of java prog. Lang. and we can never have a function without an Object


Syntax:  (argument) -> (body)


1
Runnable r1 = () -> System.out.println("My Runnable");


In the above code, Runnable is a functional interface so we can use Lambda.
Since run() has no arguments,  we have no arguments passed.

Advantages of Lambda expressions:
  1. Reduced lines of code.
  2. Pass method into behaviours
  3. High efficiency