Learning java 8 default methods . This link like any other resource on internet says
In ‘the strictest sense’, Default methods are a step backwards beca
If there is a requirement to add new method to an interface, clients which use existing interface will be broken as classes needs to implement all methods in the interface.
In this scenario, default and static methods can be used. These methods can have body and clients don't need to implement them, so existing implementations work without any changes.
For example, if you want to enhance interfaces to add methods which accept lambda expressions, you can use default methods.
Before Java 8, interfaces
could have only abstract methods
. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface
then its implementation code has to be provided in the class implementing the same interface.
To overcome this issue, Java 8 has introduced the concept of default methods
which allow the interfaces to have methods with implementation without affecting the classes that implement the interface
.
The default methods
were introduced to provide backward comparability so that existing interfaces
can use the lambda expressions without implementing the methods in the implementation class. Default methods
are also known as defender methods
or virtual extension methods
.
To overcome that we could have had one class providing implementation of these default methods and then implementing class like arraylist etc could have extended that.
Your suggestion would work only for standard JDK classes (since they usually extends some base classes such as AbstractCollection
and AbstractList
, were the implementation of the new methods can be added).
What about custom classes that implement JDK interfaces? If, for example, you have a class that implements List
but doesn't extend some JDK List
implementation, you should be able to switch to Java 8 without having to implement new methods in your class.
With default
implementations of new methods in the List
interface, you don't have to touch your custom class. You can later add a custom implementation to those methods if you are not satisfied by the default implementation.