Why java main method must be static

Why java main method must be static

This is what I think of the recent programming problem, check some information, to sum up here.

Source: https://www.cnblogs.com/numen-fan/p/7163745.html

  1. From the perspective of running a Java program, in time java program runs, JVM will go to the class corresponding to the class file for a public static void main (String [] args) were running, run by the main method is a specific thread main carried out, the program will run until the end of the main thread or non-daemon thread terminates. So, when you see "Exception in Thread main" such as: Excpetion in Thread main: Java.lang.NullPointedException, it means an exception from the main thread. If you can not find the main method, then it will throw NoSuchMethodError: main exception and stop the execution.
  2. But the program runs angle just goes to show a deeper level, because the main method is static, JVM calls this method does not need to create any instance that contains the main method, otherwise due to create an instance of the main class, the constructor can be heavy load, JVM would not be able to determine which method to call.

Furthermore, since the main method is public, that is, we want to be called as a class method, so you want to make public. And because the return value of the main method does not make sense, it is set to void.

It is because the main method is static, so all the methods it calls directly must be static, the corresponding variables used in these methods will have to be static variables. The "static member variables of the class must be initialized, if not global static variable initialization is initially 0, the function of static variables will initially function in the first run, but only once the initial" so it requires us to be variable initialization.

If you are using a non-static method or non-static variables how to do? The main method pulled out, create a startup class just fine

Guess you like

Origin www.cnblogs.com/jiading/p/11917019.html