Why the main program in Java is put into a class?

后端 未结 9 413
囚心锁ツ
囚心锁ツ 2020-12-28 17:37

Why does the main method have to be put into a class? I understand the main ideas of OOP but I cannot get why the main program is defined within a class. Will such a class i

相关标签:
9条回答
  • 2020-12-28 17:59

    It does simplify the design of the virtual machine. Since virtual machine already knows how to run a static method of a class then it can treat the main method just as any other static method.

    If you put the main method in any other construct other than a class then the VM has to be modified to know about another construct complicating things even more.

    0 讨论(0)
  • 2020-12-28 17:59

    What @Bombe said. I would add that to OO purists, the fact that the entry class is not instantiated is a misstep. The reason is the static main prevents someone from writing a family of main classes that share the same main() method written using a template method pattern.

    If Java had been written to instantiate the main class and invoke the main method, users would have enjoyed the benefits of inheritance and interfaces.

    0 讨论(0)
  • 2020-12-28 18:06

    Main in java is a static method, therefore the class it's in doesn't need to be instantiated into an object, the class simply needs to be loaded.

    0 讨论(0)
  • 2020-12-28 18:07

    The main reason is so that multiple classes can have a main method. So a codebase can have many "entry points" and one just uses the class to specify which one is called. Also, this is inline with the OO design where (almost) everything is an object.

    0 讨论(0)
  • The Java Virtual Machine (JVM) has to start the application somewhere. As Java does not have a concept of “things outside of a class” the method that is called by the JVM has to be in a class. And because it is static, no instance of that class is created yet.

    0 讨论(0)
  • 2020-12-28 18:19

    As we know main is the entry point for the JVM to start. And in java there is nothing except classes and interfaces. So we have to have a main method in the class that too it should be a public class. and the main should always be public static, because it should be accessible for JVM to start and static because it starts without creating any objects

    0 讨论(0)
提交回复
热议问题