简体   繁体   中英

When is java main method called?

  1. I have a class(1) having some constructors(arg and no args). In another class(2) an object of Class 1 is created using new constructor(). So will main method get called in this case?

  2. Ideally when is main method called in any class?

Any class can have a main method. For example, both your Class(1) and Class(2) classes can have a main method, but only one will be called once when your program is ran.

When you run the program, for example, java class1 - you tell Java that you wish to START the program using the main method of Class(1). This can be confusing, as you'd think Java would execute each and every main method it finds, but that's not the case. Once Java has found and ran the main method in the class you specified, it will ignore all future main() methods it may find as it's already executed a main method for your program.

You can think of main() as the door that leads into your program, once in, the computer won't try to come in again, it's already in the program! I hope this helps you a bit.

main是一个静态方法,是程序的入口点,并且被调用一次 (除非你明确地调用它),当程序启动时,不是为每个对象初始化。

The main method is only called in two situations:

  1. By the Java Virtual Machine to start the application
  2. By another method (possibly in another class) calling the main method, though while this is correct Java it is not best practise

main isn't automatically called on the instantiation of a class - as a static method its enclosing class does not even need to be instantiated for it to be callable.

Constructor methods on the other hand are called when a class is created.

当你运行class2(应该包含main方法)时,将调用main方法。

Your main method will be called by something which does not reside within your program and will be called once to kick off your program. Take a look here for more information. As regarding where you should place it, there is no real restriction on its location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM