Reputation: 21
Normally, an interface would be frozen once released into production.
Hence, if you need added functionality, your option in Java would be to extend an existing interface into a new interface, which describes the added functionality.
This ensures backward compatibility in the sense that you do not break the contract specified in the original interface, and you are free to implement the new interface to describe that you a new version of a particular class with additional functionality.
However, in Java 8 default method implementations were introduced to interfaces, enabling the specification of additional methods in existing interfaces to ensure backwards compatibility. However, I do not see why you would opt for this option over the previous one - and while doing so open up for serious mistakes in terms of creating poor quality code.
Could someone elaborate on this?
Upvotes: 2
Views: 717
Reputation: 892
It is obvious that the most important reason for introducing default methods in Java8 is backward compatibility. As you mentioned, before this feature, to add a new method to the interface class we should create an inherited class and it is absolutely not an effective way. Because it made developers change all object types if they wanted to use newly developed features.
To understand the importance of the default method, consider how much changes were needed to add forEach
method to Iterable
interface. As you know Iterable
is the parent of Collection
which is the parent of all existing type of lists in java. What a huge change needed to add a simple method to the Iterable
without introducing the default
method!
In addition, right now I'm benefiting default methods to reduce code writing and I don't know why it is not mentioned on any websites. A method behavior can be the same in some inherited classes and I can easily implement the behavior in parent interface using the default method and clearly change the behavior everywhere I want. However this is not a big deal, but it really makes me comfortable with development.
Upvotes: 0