Before Java 8, the interface only contains method signatures. With Java 8 new feature Default Methods or Defender Methods,
you can include method body within the interface.
All you need to do is add "default" keyword infront of the implementation method with in the interface.
This is the new way of declaring the method body in Java 8 for an interface, default methods comes along with implementation.
Why do we need to implement a method within the interface?
Let's say you have an interface which has multiple methods, and multiple classes are implementing this interface. One of the
method implementation can be common across the class, we can make that method as a default method, so that the implementation is common for
all classes.
How to work with existing interfaces?
Second scenario where you have already existing application, for a new requirements we have to add a method to the existing
interface. If we add new method then we need to implement it through out the implementation classes. By using the Java 8 default method we
can add a default implementation of that method which resolves the problem.
When working with multiple inheritance:
If we have two interfaces, one with default method and another with just method signature (normal way of defining method in the
interfaces).
Refer Java 8 Interface Default Methods for more details.
|