Prior to java8, interface in java canonly have abstract methods. All the methods of interfaces are public and abstract by default.
Java 8 allows the interfaces to have default and static methods.
The reason we have default methods is to allow developers to add new methods to interfaces without affecting the classes that implements these interfaces.
For eg: if classes A,B,C implements interface XYZ interface then if we add a new method to interface, we have to change the code in all
the classes (A,B,C) that implements this interface. But imagine if there are hundreds of classes implements an interface then it would be
difficult to change code in all classes.
Default methods can be added to any existing interface and we do not need to implement these methods in implementaion classes mandatorly, Thus we can add
these default methods to existing interface without breaking the code.
An interface can have :
Java interface default methods will help us to extend interfaces without having the fear of breaking implementation classes.
Default methods enable new functionality to be added to interfaces of libraries and have introduced as a mechanism to extending interfaces in a backward compatible way.
Java 8 interfaces default methods will help us in avoiding utility classes, such as all the collections class methods can be provided in interfaces itself.
Java interface default methods will help us in removing base implementation classes, we can provide default implementation & the implementation classes can chose which one to override.
Major reason to introduce default methods in interface is to enhance the collections API in java 8 to support lambda expression.
If any class in hierarchy has a methods with same signature, the default methods becomes irrelevant. A default method cannot override a method
from java.lang.object. It's because object is a base class for all the java classes. So even if we have Object class methods defined as default
methods in interfaces. It will be useless because Object class method will always be used. That's why we can't have dafault methods that are overriding Object class methods.
Java interface dafault methods are also reffered to as 'defender methods' or 'Virtual extention methods'.
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development.
Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : email@example.com #Contact : 98722-46056