Java, Software Development

Java – Where can we place the public static void main method?

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.

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.

Even IDEs like Intellij allow this. For example, when we run the codes, we get the following output. Cool, right?

public static void main in Java interfaces

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.

When we run the codes, we get the following output.

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.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like