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

前端 未结 5 1026
北荒
北荒 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 06:48

    From Brian Goetz's in the comments:

    I think you have the question backwards. The question is not "should main methods be allowed", it is "should we have explicitly disallowed main methods now that static methods are permissible in interfaces" (or, equivalently, exclude interface classes as targets for the java launcher.) This would have been adding extra rules just to exclude something some people perceive as weird (but not dangerous) -- and that's a losing game. You want to define as few new rules as you can reasonably get away with -- because otherwise you get mired in complexity.

    0 讨论(0)
  • 2020-11-29 06:55

    In Java 8 an interface can have static methods. Since the main method is also a static method, it will allow it.

    We can declare common helper methods using these static methods.

    0 讨论(0)
  • 2020-11-29 06:58

    More of an addendum: maybe one thought here is to resemble what you can do with the Application trait in Scala:

    object Main extends Application {
      Console.println("Hello World!")
    }
    

    simply by extending Application, you turn a class into something that runs.

    0 讨论(0)
  • 2020-11-29 07:01

    I second the answer of @jb-nizet. There is no "desparate need" for this, but it removes an unnecessary restriction. E.g. one example is, that you can now declare a factory method within the interface:

     public interface SomeService {
    
       public static SomeService getInstance() {
         // e.g. resolve via service provider interface
       }
    
       ...
    
     }
    

    Before Java 8 we needed always a separate factory class. One favorite example is the google app engine API.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题