Interface Default Methods in Java 8
Want to learn more about interface default methods in Java 8? Check out this tutorial to learn how using this new feature.
Join the DZone community and get the full member experience.
Join For FreeJava 8 introduces the “Default Method” or (Defender methods) feature, which allows the developer to add new methods to the interfaces without breaking their existing implementation. It provides the flexibility to allow interface to define implementation which will use as the default in a situation where a concrete class fails to provide an implementation for that method.
Let consider a small example to understand how it works:
public interface oldInterface {
public void existingMethod();
default public void newDefaultMethod() {
System.out.println("New default method"
" is added in interface");
}
}
The following class will compile successfully in Java JDK 8:
public class oldInterfaceImpl implements oldInterface {
public void existingMethod() {
// existing implementation is here…
}
}
If you create an instance of oldInterfaceImpl:?
oldInterfaceImpl obj = new oldInterfaceImpl ();
// print “New default method add in interface”
obj.newDefaultMethod();
Why the Default Method?
Reengineering an existing JDK framework is always very complex. Modifying one interface in a JDK framework breaks all classes that extend the interface, which means that adding any new method could break millions of lines of code. Therefore, default methods have introduced as a mechanism to extend interfaces in a backward-compatible way.
Default methods can be provided to an interface without affecting implementing classes as it includes an implementation. If each added method in an interface is defined with implementation, then no implementing class is affected. An implementing class can override the default implementation provided by the interface.
For Java 8, the JDK collections have been extended and the forEach
method is added to the entire collection (which work in conjunction with lambdas). With the conventional way, the code looks like below:
public interface Iterable<T> {
public void forEach(Consumer<? super T> consumer);
}
Since this result each implementing class with compile errors, a default method added with a required implementation in order that the existing implementation should not be changed.
The Iterable interface with the Default method is below:
public interface Iterable<T> {
public default void forEach(Consumer<? super T> consumer) {
for (T t : this) {
consumer.accept(t);
}
}
}
The same mechanism has been used to adda Stream in the JDK interface without breaking the implementing classes.
When to Use Default Method Over Abstract Classes
Abstract Classes Versus Interfaces in Java 8
After introducing Default Method, it seems that interfaces and abstract classes are the same. However, they are still a different concept in Java 8.
The abstract class can define constructors. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Hence, both are used for different purposes and choosing between two really depends on the scenario context.
Default Method and Multiple Inheritance Ambiguity Problems
Since Java classes can implement multiple interfaces and each interface can define a default method with the same method signature, the inherited methods can conflict with each other.
Consider the example below:
public interface InterfaceA {
default void defaultMethod(){
System.out.println("Interface A default method");
}
}
public interface InterfaceB {
default void defaultMethod(){
System.out.println("Interface B default method");
}
}
public class Impl implements InterfaceA, InterfaceB {
}
The above code will fail to compile with the following error:
java: class Impl inherits unrelated defaults for defaultMethod() from types InterfaceA and InterfaceB
In order to fix this class, we need to provide a default method implementation:
public class Impl implements InterfaceA, InterfaceB {
public void defaultMethod(){
}
}
Further, if we want to invoke default implementation provided by any super interface rather than our own implementation, we can do so as follows:
public class Impl implements InterfaceA, InterfaceB {
public void defaultMethod(){
// existing code here..
InterfaceA.super.defaultMethod();
}
}
We can choose any default implementation or both as part of our new method.
Difference Between Default Method and Regular Method
Default Method is different from the regular method in the sense that default method comes with default modifier. Additionally, methods in classes can use and modify method arguments as well as the fields of their class, but default method, on the other hand, can only access its arguments as interfaces do not have any state.
In summary, Default methods enable us to add new functionality to existing interfaces without breaking older implementation of these interfaces.
When we extend an interface that contains a default method, we can perform following,
- Not override the default method and will inherit the default method.
- Override the default method similar to other methods we override in subclass..
- Redeclare default method as abstract, which force subclass to override it.
References
Published at DZone with permission of Muhammad Ali Khojaye, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments