Interface changes in Java 8
One of the biggest design changes in Java 8 is with the concept of interfaces. Prior to version 8, Java supported only method declarations in interfaces. But from Java 8, we can have default methods in the interfaces,which can have implementation as well.
Let’s take an example : The below code will compile in Java 8.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public interface java8Interface { default public void display(){ System.out.println("Inside [java8Interface] [display] "); } } public class Java8InterfaceImpl implements java8Interface { public void draw(){ System.out.println("[Java8InterfaceImpl][draw]"); } } public class TestInterface { public static void main(String[] args) { Java8InterfaceImpl interfaceImpl= new Java8InterfaceImpl(); interfaceImpl.display(); } } |
Output:
Inside [java8Interface] [display]
Why Defaut Method?
Modifying an interface
in any application framework
breaks all classes
that implements the interface
. For example adding any new method
in an existing interface could break lots of lines of code
. Default methods can be added to an interface without affecting implementing classes as it includes an implementation. If each added method
in an interface
defined with implementation then no implementing class is affected. An implementation class
can also override the default implementation provided by the interface. Default methods will help us in extending interfaces without having the fear of breaking implementation classes.
Default Method and ambiguity Problem
Lets understand the ambiguity issue with the below example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public interface Java8InterfaceA { default public void display(){ System.out.println("Inside [java8InterfaceA] [display] "); } } public interface Java8InterfaceB { default public void display(){ System.out.println("Inside [java8InterfaceB] [display] "); } } public class Java8InterfaceImpl implements Java8InterfaceA,Java8InterfaceB { } |
As mentioned in the above code, if we try to implement two interfaces which are having same methods , we will get compilation error as below.
Duplicate default methods named display with the parameters () and () are inherited from the types Java8InterfaceB and Java8InterfaceA
In order to fix this error we need to provide default method implementation:
1 2 3 4 5 |
public class Java8InterfaceImpl implements Java8InterfaceA,Java8InterfaceB { @Override public void display() { } } |
Further, if we want to invoke default implementation provided by any of super
interfaces
rather than your own implementation, we can do so as follows,
1 2 3 4 5 6 |
public class Java8InterfaceImpl implements Java8InterfaceA,Java8InterfaceB { @Override public void display() { Java8InterfaceA.super.display(); } } |