Question

Was introducing default methods to java inevitable? As far as I know multiple class inheritance was not introduced to avoid difficulties with the method signature clash in base classes.

So we avoided it with classes and on the other hand we introduce this problem with default methods as we have to override default method if it exists with the same signature in two or more interfaces that we implement.

Is the cost of updating old systems to newer versions of interfaces without using default methods greater than cost of using language with garbage in its syntax?

Was it helpful?

Solution

The reason that default methods were introduced was that without them, it's impossible to add new methods to an interface and maintain backwards compatibility. As explained here:

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

They were introduced in Java 8 along with the stream APIs. Looking at the default methods that were added to Collection, it starts to become clear. The addition of the streaming methods such as stream, parallelStream, and spliterator would break every existing Collection implementation outside of the JDK.

This is clearly the primary driver of the addition. I think the worries around them have proven to be unwarranted. There is no ambiguity in the spec around how clashes are handled. They also have some nice features aside from the above. For example, there's no longer a need to implement a remove method in an Iterator implementation because it has a default implementation.

So to the point of your question which I initially failed to answer:

Is the cost of updating old systems to newer versions of interfaces without using default methods greater than cost of using language with garbage in its syntax?

So whether default methods are 'garbage' is highly subjective but the first part is answerable. The Collection interface is one of the most implemented interfaces in Java code. There is a truly immense amount of code that would need to be updated if a non-backwards-compatible changes were made to it. The cost seems immeasurable and I think the result would be that a lot of Java code would never be able to run on 1.8 or better given it's history of backwards-compatibility.

We could ask whether new features such as this could be added in another way, such as by using wrappers. Perhaps but such an approach tends to be unwieldy and create a lot of extra code. In the years since this was introduced, I've seen no evidence that it has caused any significant issues.

Licensed under: CC-BY-SA with attribution
scroll top