public static final Function<String, Set<String>> MAPPING_FUNCTION = new Function<String, Set<String>>() {
@Override
public Set<String> apply(String s) {
return new HashSet<>();
}
};
MAPPING_FUNCTION已经是接口Function<String, Set<String>>的一个实例了啊?
This is not an instance of an interface, but an instance of an anonymous inner class that implements the interface.
Didn’t you notice there’s a brace after it? It is obviously different from the form we usually use
A a=new A()
.It is recommended that you take a look at the related knowledge of internal classes.
This is a way of writing anonymous inner classes. In fact, this way of writing is equivalent to writing a new class and then implementing the interface.
The problem is that creating a new class just to implement a method of the interface is too fussy, so most writing methods will directly write an anonymous inner class.
Because we don’t pay attention to the name of the class, we only pay attention to its specific implementation, which is also a common usage scenario of anonymous inner classes.
Chapter 6 of "Crazy Java Lecture Notes" has a detailed explanation. If you don't want to read the book, just search for "Anonymous Internal Class"
Anonymous inner class is equivalent to a class that implements this interface. Just write the declaration and implementation together.