Default Methods in Java8
If a class implements an interface, Then that class need to provide implementations for all the methods declared in an Interface. Consider the following code snippet.
This can be a trouble if we need to add a new method to the interface so as to extends the functionality of our Interface, as adding a new method to Interface will require all child classes of that interface to implement the new method.
So, To solve this problem default methods were introduced in java 8.
Consider following code snippet
So, In the above code snippet, we have added newMethod() as a default method in InterfaceParent . And though ClassChild don’t have implementation for newMethod() the code compiles without any errors.
Now we can add a new class implementing the newMethod(), or modify existing classes where the new method is required. Thus we are able to extend the functionality of the current interface without modifying the existing class ClassChild. Following code for the new class.