Java / Methods
Explain the Default method for interfaces in Java 8.
In Java 8, a new feature "default method implementation for interfaces" is introduced that facilitates backward compatibility for the old interfaces to leverage the lambda expression capability of Java 8 and also existing libraries implementing these interfaces need not have to provide its implementation for the new functionality/method added to the interface.
For example, java.util.List or Collection interface does not have forEach method declaration. Thus, calling such methods will break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not have to implement the same.
Thus default methods enable you to add new functionality to the interfaces of your libraries and ensure backward compatibility with the codes written using the older versions of those interfaces without having to implement the new functionality.
For creating a default method in Java interface, we need to use default keyword with the method signature.
The default methods are non-static and can be accessed from the Implementing class object as shown in the below example.
Java interface default methods are also known as Defender Methods or Virtual extension methods.
A default method cannot override a method from java.lang.Object class as interfaces does not extend Object.
Compilation error occurs when a class tries to implement two or more interfaces having a default method with the same signature.
Other than multiple inheritance, there is no significant difference between an abstract class and an interface in Java 8 by the addition of default method feature.
More Related questions...