Before Java SE 8, interface was just an abstraction of things, used to define unified abstractions and abstract behaviors and attributes that describe things.
However, in Java SE 8, the static behavior of behaviors and things that can be added to the default implementation in interface is added.
A. Why?
Java iterates over so many versions and primarily uses evolutionary ideas rather than refactoring (to ensure compatibility with history).
This makes it easy to get a lot more difficult to deal with, and the interface is trained after it is released, unless we can update all implementations of that interface at once. For example, a history interface has many implementations, need to add a behavior in the history interface, so long need to implement the behavior in all its implementation, then undoubtedly hinder the evolution, adding the default method to the interface can make the interface can still evolve gradually, which is also in line with the law of natural things have been developing.
And, son. In Java SE 8, a functional interface is introduced, and the default methods and static methods in the interface are used to break through the individual method limitations of the functional interface.
Two. Example
The default method in the interface
public interface TestDefaultMethodApi { default void print(String msg) { System.out.println(msg); }}
Static methods in the interface
public interface TestStaticMethodApi { static void utilMethod(String msg) { System.out.println(msg); }}
Three. Use
Default method:
- Can be used in a function-type interface
- The public behavior can be abstracted as the default method, which is the default method in all implementations-this can refer to collection
- You can add a default method to an already published interface, allowing the interface to behave in a new way and continue to evolve
static method:
- Statically more property interfaces or types behave themselves, and some tool methods that are nearly interface-coupled can be used as static methods to achieve high-cohesion
Four. Points of caution used
interface, the default method is defined in the implementation, but the default method does not need to be implemented, and if the implementation does not overwrite the default method defined in the interface, the ability to invoke the default method in the implementation is the default method implemented in the interface
The implementation of the default behavior can be overridden in a specific implementation, such as vector vectors that cover the Removeif in collection
The default method can only be defined in the interface, and if it is defined elsewhere, the compilation error
Reference
Deep understanding of Java 8 Lambda (language article--lambda, method reference, target type and default method)
Default methods and Static methods in Java 8--interface