The default method Java8

The default method

  In Java8 added default method is mainly to support library designers, so that they can easily write an improved interface. This approach is important because you will encounter more and more of the default method in the interface, but relatively few actually need to write the default method of programmers, but they only help to improve the program, and not for writing any specific program.
  Two Java8 sample code:

List<Apple> heavyApples1 =
	inventory.stream().filter((Apple a) -> a.getWeight() > 50).collect(toList());
List<Apple> heavyApples2 = 
    inventory.parallelStream().filter((Apple a) -> a.getWeight() > 50).collect(toList())	

But there is a problem: Before Java8, List does not stream or parallelStream method, it did not implement the Collection interface. These methods can not, the code will not compile. The easiest way is to join the stream method in the Collection interface, and add to realize ArrayList class.
  But if to do so for users is a nightmare. There are many alternative Collections Framework interfaces are implemented using Collection API. However, a new method is added to the interface, means that all entity classes must provide an implementation. Language designer can not control all existing implementations Collections, so how to change a published interface without disrupting existing achieve it?
  Java8 solution is to break the last link - Interface can now include implementation class does not provide a way to achieve the signature. The method of missing body is provided with an interface, and not by the implementation class.
  This gives designers the interface provides a way to expand the interface, without breaking existing code. Java 8 to use the new interface statement default keyword to indicate this.
  For example, in Java 8, the method can now be used directly on the List sort. It is the default method for the interface shown in Java8 List following implementation, it calls Collections.sort static method:

default void sort(Comparator<? super E> c){
	Collections.sort(this,c);
}

  This means any entity classes List do not need to explicitly implement sort, but in previous versions of Java, unless a sort of realization, otherwise it will fail in these entity classes recompile.

Published 75 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/zhengdong12345/article/details/102528020
Recommended