Default Methods In Java

Default methods allows us to add new functionality to new or existing interfaces without breaking the existing functionality of legacy code.

Prior to Java 1.8 interfaces did not allow default interfaces and it was very difficult to modify an existing interface without impacting the class which implemented the interface.For instance if a new method is added to an interface ,it  needs to be implemented in all the classes implementing that interface.

Example

Consider the following interface which is an existing piece of code:-

The interface is implemented by various branches of the Good Food Restaurant.

We later plan to add the restaurant working hours .But if we add it to the interface ,the method needs to be implemented in all the three classes.This can be a lot of work especially in big projects where the interface is implemented in several different classes and multiple new method are added in the interface.

Default method comes to the rescue in all these cases.With default methods its not mandatory for an implementing class to implement the default method , its optional.

A default method is defined in an interface and if the implementing class do provide the implementation of the default method then it overrides the default method definition.Here’s the summary when you implement an interface that contains a default method:-

  • Do not redefine the default method in the implementing class ,which lets you use the default method definitions whenever it is called.
  • Redefine the default method, in this case it is overridden

Extending an interface with a default method

The following rules apply when you extend an interface that contains a default method along with one more scenario:-

  • Do not redefine the default method in the implementing class ,which lets you use the default method definitions whenever it is called.
  • Redefine the default method, in this case it is overridden
  • Redeclare the default method which makes it abstract.

That’s all about default methods in Java.I hope you enjoyed reading this articles.

Published by Anna

Just a simple girl who loves to code. .I am primarily a Java developer by profession and I am here to share my love for coding with you all I hope you enjoy reading my blog. Happy Coding Guys :-)

Leave a comment

Your email address will not be published. Required fields are marked *