Preferences of abstract classes over interfaces in Java 8

Now we know that Java 8 introduced interface 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 also introduced a diamond problem that it avoided in previous versions.

The default methods are not necessarily necessary to override.
But when the problem with the diamond is related to the use of interfaces, the class implementing these interfaces must override the default methods.

So now I have three questions:

  • Why do we need default methods?
  • Could we have multiple inheritance through classes, instead of using default methods in interfaces?
  • And what was the need to avoid the problem with diamonds in previous versions, if they still had to present it in Java 8?

Any good explanation or any link for an explanation?

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

So, I want to know if abstract classes are more specific and can have constructors,
and in any case, Java introduced a problem with diamonds, why should we have interfaces now? Won't abstract classes be good enough as independent classes for multiple inheritance?

+6
source share
3 answers

No, he did not repeat the diamond problem, because the interfaces still cannot have any state, and the default methods may not be final.

So, when you decide to implement two interfaces, you still have the freedom that you want to implement by default, either by choosing one of the provided default implementations, or by providing your own implementation. But you will never have the problem of inheriting a conflict state from both interfaces or inheriting two different final methods and the inability to resolve the conflict.

So, here are the answers to your questions:

  • To implement new methods in existing interfaces without breaking backward compatibility: existing implementations will automatically implement these methods, since their implementation is in the base interface.
  • No, because it will lead to a diamond problem.
  • Unnecessary
+15
source

Regarding point 1:

To support a lambda expression for all collection classes, such as the forEach method, you had to add something that would be backward compatible.

see this video for details Lambda Peak under the hood

+2
source
  • The default methods can improve the existing interface, while ensuring binary compatibility with previous versions of the interface for existing users.

More details here https://docs.oracle.com/javase/tutorial/java/IandI/nogrow.html

0
source

Source: https://habr.com/ru/post/971233/


All Articles