Many Java programmers are only familiar with having the public static void main in a class to start the application. However, there are other places where we can define this static method and still start up a Java application. This post shows where we can start up our application via, no less than the public static void main.
The typical public main method
Normally, we place the main method in a bootstrap class, a single entry-point of the whole program. Consider the following codes.
1 2 3 4 5 6 | public class MyClass { public static void main(String[] args) { System.out.println("Start up the whole application"); // ... } } |
Nothing special in the codes. All Java programs start from this static method. However, during development or debugging, we temporarily create such public methods in other classes to bootstrap from those classes. Besides classes, there are other places we can put that static method and start the application from.
A public main method in an Interface
Many may find this surprising but placing a static method in an interface is legal in Java. Therefore, we can define a public static void main method too! When we do that, we can start the application from that interface.
1 2 3 4 5 6 7 | package com.turreta.publicstaticmain; public interface MyInterface { public static void main(String[] args) { System.out.println("In an interface"); } } |
Even IDEs like Intellij allow this. For example, when we run the codes, we get the following output. Cool, right?
A public static main method in a Java abstract class
Next, we can place the main method in an abstract Java class. This fact may not surprise many Java developers because of their affinity to Java classes.
1 2 3 4 5 6 7 | package com.turreta.publicstaticmain; public abstract class MyAbstractClass { public static void main(String[] args) { System.out.println("In an abstract class"); } } |
When we run the codes, we get the following output.
1 | In an abstract class |
Java public static void main method in anonymous and Inner classes?
Have you noticed what the class, interface, and abstract classes in our codes have in common? They all use the Java public access modifier, which, in effect, makes the public static void main method visible to the JVM at startup. Therefore, placing the main method in anonymous and inner classes will not work. The JVM will not be able to detect it in those places.
This post is part of a reboot Java tutorial.