Now assume we need to add new method factorial () method in our interface to provide this method’s definition to few of the subclasses, in our example it is SimplePlusFactorialCalculator and ScientificCalculator but not SimpleCalculator
How can we do it ?
We need to add it in interface but once we add its declaration in interface , what is the consequence on all the implemented classes?
Yes we need to implement in all the implemented classes including those classes which does not require that method(in our example it is SimpleCalculator). So what if 1000 such classes implements this interface, then all 1000 classes needs to be changed which is not good all the time because some classes need it and some classes may not need it.
So java 8 feature ‘default method’ will resolve this kind of backward compatibility problem easily without changing the irrelevant sub classes.
Steps to resolve using default method
Step 1 – add a method definition inside the interface but prefix signature with default keyword.

In Java 8 we can declare as well as define methods within interfaces as we discussed so far....
but how it is different from Abstract classes ? we can do the same with abstract class
Abstract class can not be instantiated (i.e. objects can not be created for it) and which may contain method bodies.
So abstract class and interface with default method both are same right ?
No. they are not same and not one is the replacement of other. Each will serve its own purpose.
. Abstract class can have constructors and member variables. Whereas interfaces with Java 8 default methods cannot. It cannot have constructors and member variables.
Default method should be used for backward compatibility which means whenever we want to add additional functionality in an existing legacy interface, we can use default methods without breaking any existing implementer classes but same cannot be achieved with abstract classes which forces sub classes to adopt the change.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com