Why does a Java program require a “main()” method?

2019-02-27 14:40发布

问题:

It is just a naming convention? Why can't any method be called while executing a program from a shell e.g

$> java myPackage.MyClass.myOwnEntryPoint(String[] str)

回答1:

Yes, that's a naming convention, inherited from C. The advantage is that this way, it's very simple to find out which method is supposed to be the main method just by looking at the code.



回答2:

The main method is the entry point that the java program for running Java applications (as opposed to applets or other things) looks for. As far as I'm aware, there's no way to tell java to look for a different method instead, so it's not just a naming convention; if you want your application to run (via the standard java tool, anyway), you want to give it a main method with the appropriate signature. (You can play games with static initializers, but that's another thing entirely.)

The name main is inherited from C, but it's not just a convention.