search

Home  >  Q&A  >  body text

interface - Java中接口不能被实例化,那么如下的代码怎么理解?

    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中文网2812 days ago440

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 17:55:33

    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.

    reply
    0
  • 黄舟

    黄舟2017-04-17 17:55:33

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:55:33

    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"

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:55:33

    Anonymous inner class is equivalent to a class that implements this interface. Just write the declaration and implementation together.

    reply
    0
  • Cancelreply