What is “static”?

2020-01-29 07:14发布

I'm beginning to program in Java.

public static void main(String[]args)

A book said that I should use static in this case, but doesn't clearly say why I should or what it means.

Could you clarify this?

标签: java static
7条回答
何必那么认真
2楼-- · 2020-01-29 07:49

In this particular case the main method must be static, because of the way the JVM will start loading classes and creating objects. When you start a Java program the JVM will look for the definition of the class that was passed to it and load it. So java MyClass will result in loading the definition of the MyClass class.

By definition a Java program will start executing in the main() method of the class that was passed to the JVM as the class to load initially. At this point in time no instance (object) of type MyClass has been created, so the main method has to be static to allow the start of the execution of your program.

If you want to see which classes are being loaded during the execution of a Java program you can use the -verbose:class command line option.

查看更多
登录 后发表回答