Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

class

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 instantiated somewhere? I mean there is no code outside the class. What is a reason to define a class and never use objects of this class?

like image 623
Roman Avatar asked Jan 28 '10 15:01

Roman


People also ask

Why is main inside a class in Java?

Because that is how the language was designed. The JVM first loads the class containing the main function and then calls the main() method. Without loading the class, main() cannot be called, i.e, main() doesn't exist without its enclosing class.

Does main need to be in a class in Java?

Yes, the Main method is required to run a function although a java class can be without the Main method.


2 Answers

While it's true that java has no concept of methods outside of classes, it would be pretty easy to allow developers to skip all the broilerplate of actually writing out the class definition and simply let people write the main function directly, if they wanted too.

But back when people were developing java, people were more dogmatic about OO then they are now, and that probably played a big part. Think of it as an example of Opinionated software

It has one useful feature though, which that you can main functions to any class and launch them as programs. It's handy for testing specific features of those classes when you're working on them. If main() had to be in a separate file, and not part of a class, that would make things difficult. What if you want more then one main() function? What if you wanted to write functions to be called by main outside of the class? Would they go in a global namespace? Would multiple main() functions collide?

Not like those problems are impossible to solve, but other then a little extra typing, which can be especially annoying for newbies the current solution isn't too bad, especially since IDEs will generate the basic class structure when you create a new file.

like image 22
Chad Okere Avatar answered Oct 22 '22 12:10

Chad Okere


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.

like image 161
Bombe Avatar answered Oct 22 '22 13:10

Bombe