Search code examples
javainterfaceabstract-classjava-8diamond-problem

Preferences of abstract classes over interfaces in Java 8


Now, we know that Java 8 has introduced default and static methods in interfaces.
Interfaces were originally introduced in Java to avoid the diamond problem that occurred in C++, in multiple inheritance.

But along with the introduction of default methods in interfaces in Java 8, now, Java has also introduced the diamond problem, which it avoided in previous versions.

Default methods are not compulsorily needed to be overridden.
But when a diamond problemoccurs using interfaces, the class implementing those interfaces must override the default methods.

So now, I have three questions in my mind:

  1. Why is the need to have default methods?
  2. Couldn't we have multiple inheritance through classes itself, in place of having default methods in interfaces?
  3. And what was the need to avoid diamond problem in the previous versions, if they had to introduce it in Java 8 anyway?

Any good explanation or any link for explanation?

PS I did not find any link on the internet containing any good article on this.
All they said is that an abstract class gives you more concreteness.
As in, abstract classes can have constructors but interfaces cannot.

So again, I want to know, If abstract classes are more concrete, and can have constructors,
and anyways Java has introduced the diamond problem, why should we have interfaces now? Wouldn't abstract classes be good enough as a stand alone for multiple inheritance?


Solution

  • No, it didn't reintroduce the diamond problem, because interfaces still can't have any state, and default methods may not be final.

    So, when you choose to implement two interfaces, you still have all the freedom you want to implement the default methods, either by choosing one of the provided default implementations, or by providing your own implementation. But you'll never have a problem of inheriting conflicting state from both interfaces, or inheriting two different final methods and not being able to resolve the conflict.

    So, here are the answers to your questions:

    1. To be able to introduce new methods in existing interfaces without breaking backward compatibility: existing implementations will automatically implement these methods since their implementation is in the base interface.
    2. No, because that would introduce a diamond problem.
    3. Irrelevant