Why are the default interface methods?

Learning java 8 default methods. This link, like any other resource on the Internet, says

In the strictest sense, the default methods are a step backwards because they allow you to “pollute your interfaces with code. But they provide the most elegant and practical way to backward compatibility. This has made it easy for Oracle to update all Collection Classes and for you to modify existing code for Lambda.

My understanding is that java 8 dev / designer provided a default method in the interfaces so that the entire implementing class does not need to unnecessarily override the same behavior, therefore, provide backward compatibility. For example: - if the ForEach method was not the default method, each collection implementation class should implement it. Agreed.

To overcome this, we could have one class that provides the default implementation of these methods, and then an implementation of a class such as an arraylist, etc. expanded it. Thus, we could affirm both the basic principles of java and reuse and abstraction, thereby reducing interface pollution

I am sure that java 8 dev / designer has already thought about this, since they are much more recognized, and I missed something. Could someone help here so that we developers can also be on top of this as this is a significant change?

+4
source share
2 answers

To overcome this, we could have one class that provides the default implementation of these methods, and then implement a class like arraylist, etc., could extend this.

Your suggestion will only work for standard JDK classes (since they usually extend some base classes, such as AbstractCollectionand AbstractListwhether new methods have been implemented).

, JDK? , , , List, JDK List, Java 8 .

default List . , .

+5

Java 8, interfaces abstract methods. . , interface, , .

, Java 8 default methods, , , interface.

default methods , interfaces - . default methods defender methods virtual extension methods.

+1

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


All Articles