Where should I put the public static void main(String[] args) method?

I don't think it has any effect on the program output, but what class should I put the

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

method in my program? Is it better form to create a separate class, or put it in a class that does something else? If I should put it in a class that does something else, which one? Does it matter? This is really just a conventions thing. Normally I create a separate class or put it in the class that deals with the gui, but I would like to know the right way of doing it.


If you are writing very short programs (eg simple algorithms), it may seem to be more convenient to just add your main method to the class containing some basic program logic. However, for greater projects it is very helpful to separate your main method from business logic/database access/anything else that should be working as an encapsulated entity.

Main method should just give you the beginning of the chain, so that you could easily follow the workflow of your program from the very beginning. Including logic (even simple number conversion/string operations) in class containing main method could cause some unnecessary chaos, try to separate everything what you don't really need there and put it in helper classes.


When you are writing program with more than one class then main() method should be in the class with the program name.

If the program name is temp.java and there are two classes named temp and temp1 the main() method should be included in the class. Separate class is not necessary


The right way to handle this depends on your application. But, most of the times it is better to have a very simple and understandable code in your main method that reflects your application behavior in a very broad term.

链接地址: http://www.djcxy.com/p/79686.html

上一篇: Neo4j时间依赖图模型

下一篇: 我应该把公共静态void main(String [] args)方法放在哪里?