Why do we need the main method when you have static blocks

This question has been asked to someone I know. I might have thought that the main method should accept command line arguments as method parameters.

Are there any other arguments for protecting the method public static void main(String args[]) ?

+8
java
source share
5 answers
  • This allows you to check the main method
  • Allows calling the main method from other classes
  • This allows you to call the main method several times, while type initialization occurs only once.
  • This allows you to instantiate a class containing the main method without running the program.

The idea of ​​initializing the type to lock the "main" class before the application terminates is disgusting.

Can we handle this? I dare say. But I suspect that I will always write:

 public class EntryPoint { static { // Workaround for entry points being static initializers String[] arguments = getArgumentsHoweverThatHappens(); RealEntryPoint.execute(arguments); } } 

... and nothing else will touch EntryPoint .

+11
source share

Static initializers and the main method have different intentions. The main purpose of the method is to call if and only if the JVM is called with the containing class as the main class (or if it is called directly by the code). The purpose of static initializations is to initialize classes. Initializers always start, but it is possible to have basic methods that are not.

+8
source share

In addition to the above, the need for main (and not the characteristics of static blocks) is that your application needs a starting point, that is, when you run your application, you pass dozens of classes to the JVM and the JVM must know which method to call first to start and execute your application. You need to declare which point is the beginning of your application, since the JVM cannot guess it. (Sorry for my English)

+8
source share

Static blocks are designed to run after loading the corresponding class. main() , however, is the entry point to your program, and, as John said, you can call it several times.

+4
source share

Mostly due to C.

It would be nice if some public static method could be an entry point, and not just main

+1
source share

All Articles