Difference between Java 8 interface and Java 7 interface



Before Java 8, interface having only abstract methods that means method without body (implementation). But Java 8 interface can contain abstract method as well as default implemented method and interface level method (static method). That means now in Java 8 interface can contain three types of methods.

1. Abstract method
2. Default method
3. Static method

We can add a method with default implementation. By using “default” keyword. This method can override but not mandatory. Using interface name we can access static method.

Example:-
package nk.test;
public interface Java8Interface{
/*abstract method*/
 void show();
/*default method */
default void display(){
System.out.println(“default method call”);
}
/*static method*/
public static void disp(){
System.out.println(“static method call”);
}
}
Why default method?

Modify one interface in JDK framework breaks all classes that extends the Interface which means that adding any new method could break millions of lines of code. Therefore, default method have introduced as a mechanism to extending interface without affected extending class.

No comments:

Post a Comment