SengJoonHyun
SengJoonHyun

Reputation: 73

Few main() methods in one java package

I suddenly wonder that what's the difference between creating multiple main methods ,and creating one main method in a java package.

Example 1, An a.java has its main method, then the a.java method will pass some to the b.java that also has its main method.

A.java ( A.java's main method ) --(Passing some to)--> B.java (B.Java's main method )

Example 2, Not like the above, the a.java does Not have its main method but b.java only HAS its main method. Run the b.java to get some from the a.java .

Run B.java (This only has its main method) --(To get some from ) --> A.java (It does Not have its main method )

I think this is complicated to explain as text... I just want to know that what is the difference between them , and if you recommend either one of them, which one would be good ?

Upvotes: 3

Views: 95

Answers (2)

aroth
aroth

Reputation: 54806

The difference is that if you implement main() in multiple classes, then you'll have the option of running each individual class as a Java application.

Do you want or need to do this? If so, there's your answer.

Otherwise (and more typically), you have a single class that implements main(), and it interacts with or delegates to other classes by directly invoking their declared methods (which, if you're using good coding style, will be descriptively named and not called main()).

In short, implement main() when you want your class to be directly runnable as a Java application. Otherwise, don't.

Whether you have zero, one, or more than one classes implemeting main() is up to your requirements, though in most cases you'll either have zero or one.

Also note that your scope is not limited to a single package. There's nothing that says that each package should or must have a class that implements main(). In fact, most packages have none, and adding main() implementations purely to satisfy a "there should always be at least one" kind of rule would be a bad idea.

If your requirements don't call for a main() implementation, don't add one.

Upvotes: 3

Zameer
Zameer

Reputation: 1

Keeping two main methods does not make any sense. It is like you are using one main method as it is and other main as a simple method. The only thing here is the name is main(). You can set its name other than this as well. But in class A you need the main method.

Upvotes: 0

Related Questions