Why are interfaces in Java 8 allowed to have the main method?

前端 未结 5 1043
北荒
北荒 2020-11-29 06:10

Why are interfaces allowed to have a main method in Java 8?

As stated in below code it works fine and produces output properly.

public i         


        
5条回答
  •  盖世英雄少女心
    2020-11-29 07:13

    Since Java 8, static methods are allowed in interfaces.

    main() is a static method.

    Hence, main() is allowed in interfaces.

    We don't need this, since it wasn't allowed before, and yet we survived. But since static methods, by definition, are not bound to an instance of a class, but to the class itself, it makes sense to allow them in interfaces. It allows defining utility methods related to an interface (like the ones found in Collections, for example), in the interface itself, rather than a separate class).

    There is no difference between class static methods and interface static methods.

提交回复
热议问题