Any practical difference in the use of Java's static method main?

牧云@^-^@ 提交于 2019-12-12 04:13:34

问题


If I have the following Java class :

public class MyClass
{
  ...

  public static void main(String[] args) 
  {
   ...
  }
}

Is there any practical difference if I call it in the 2 different ways below ?

[1] new Stock_Image_Scanner().main(null);
[2] Stock_Image_Scanner.main(null);

回答1:


In the first one the constructor gets executed. In the second one it does not.




回答2:


main is a static function, and should not be called via an instance. It should only be called via the class name:

Stock_Image_Scanner.main(null);

In addition, null should really be changed to new String[]{}. And as stated @kg_sYy, the new way (via the instance) executes the classes constructor, which is generally unexpected and not recommended.

More info:

  • Why isn't calling a static method by way of an instance an error for the Java compiler?

  • Is calling static methods via an object "bad form"? Why?




回答3:


Just to say the same thing in yet another way:

new Stock_Image_Scanner().main(null);

Does the same thing as:

new Stock_Image_Scanner();
Stock_Image_Scanner.main(null);


来源:https://stackoverflow.com/questions/21975471/any-practical-difference-in-the-use-of-javas-static-method-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!