Java is often (rightly IMHO criticized) for overusing the class
keyword, as it can denote:
- a factory to instantiate objects (traditional classes)
- a collection of global methods (when all methods are static and there is a private constructor...the so-called "utility class" pattern)
- an application (when it holds a public static void
main
method, etc) - a wrapper for a singleton
Now several Java successors have gone with top-level object keyword to avoid the singleton usage (getting rid of #4, which is good), and Java itself, many years ago, allowed the interface
to include static methods to get rid of the ugly #2.
But since #3 in the list above is a special case of #2, why not adopt the interface for applications? For example:
interface GreeterApp {
static void main(String[] args) {
System.out.println("Hello world");
}
}
works just fine:
$ java GreeterApp.java
Hello world
I have not seen this pattern used before, but my web searching skills might need some work. But doing so allows use to use the class keyword only for factories that instantiate objects, and to use interface for collections of (static) methods, since the complaint about traditional Java application classes is that they really existed only to "house" the main method.
It may be that the use of class
for a main app is so widespread, and so traditional, that the use of an interface to house an application's main method might never have been considered. (EDIT: But see Jörg W Mittag's note in the comments that indeed the JLS authors were aware.)
But there may be more technical reasons for using classes over interfaces, or interfaces over classes, other than linguistic preferences. Are there any "kinds" of applications that call out for one or the other?
(EDIT: The question was slightly reworded to remove the opinionated tone and instead ask for specific advantages.)
main
of some specified class or interface, passing it a single argument which is an array of strings."