Unnamed classes and instance main methods in Java 21 (preview) Part II
Java 21 lets us write
void main() {
System.out.println("Hello, World!");
}
instead of
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Part I described how to get it running. This part talks about which main method is chosen.
Choosing a main
method
Consider these two instance main
methods:
void main() {
System.out.println("void main()");
}
void main(String[] args) {
System.out.println("void main(String[] args)");
}
When running the output of the this main file will be
void main(String[] args)
A void main(String[] args)
method is selected in favor of void main()
, if both a present.
Consider these two static main
main methods:
static void main() {
System.out.println("static void main()");
}
static void main(String[] args) {
System.out.println("static void main(String[] args)");
}
Again static void main(String[] args)
is selected in favor of static void main()
method. The method with more information in the method signature “wins”.
What if we mix static
and non-static
methods?
void main(String[] args) {
System.out.println("void main(String[] args)");
}
static void main() {
System.out.println("static void main()");
}
and
void main() {
System.out.println("void main()");
}
static void main(String[] args) {
System.out.println("static void main(String[] args)");
}
In both cases the static
main method is selected in favor of the non-static
method.
Since Java does not allow methods with the same name and parameter list to differ only by the static
keyword, other combinations are not possible.
Summary
JEP 445 summarizes the selected main method:
When launching a class, the launch protocol chooses the first of the following methods to invoke:
1. A
static void main(String[] args)
method of non-private access (i.e.,public
,protected
or package) declared in the launched class,2. A
static void main()
method of non-private access declared in the launched class,3. A
void main(String[] args)
instance method of non-private access declared in the launched class or inherited from a superclass, or, finally,4. A
void main()
instance method of non-private access declared in the launched class or inherited from a superclass.