interface - Java中接口不能被实例化,那么如下的代码怎么理解?
PHP中文网
PHP中文网 2017-04-17 17:53:33
0
4
434
    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>>的一个实例了啊?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(4)
Peter_Zhu

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.

Ty80

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template