Java Basics

main - Which class to put it in?

Many styles are used. The main method can be put in any class, and you will see many variations. Programs that subclass JFrame, a very common style for building GUIs, often just put it in the JFrame subclass. This style is OK, and I often use it. Defining it in a separate class is sometimes clearer for beginning students because it doesn't require that seemingly mysterious instantiation of itself.

Defining main in the JFrame subclass

Very common. This style is used by many programmers and is a common style in these examples. I believe it is the single most common style for building a GUI, although this is based only on programs I happen to see, not on a more reasonable survey.

Easier to manage. Using this style eliminates one source file, which makes reading the program generally simpler.

I've switched back and forth many times between putting main in its own class versus putting it in a subclass. The differences are minor. This is my current default style.

Defining main in its own class

Easy to understand. Most beginners understand this style easily, and feel more comfortable than when main creates an object of its own class. Defining main in a separate class is simple, and makes the code easier to understand. When main is in the same class as the GUI, there is a temptation to try to reference instance variables from main, which is a common beginner error.

Applet and application. Separating main may make it easier to change between an application and an applet without confusion. It's also possible to put main in a JApplet subclass, but again it may lead to confusion with no special advantage.

Separates unchanging code. Putting main in its own class moves unchanging window organization code away from other code so there is less confusion.

Better if additional setup. For simple programs a small main looks lonely in its own class, but as programs grow larger, main may take on more model initialization and framework responsibilities. Putting it in its own class gets you used to a style that might be useful when your programs get larger.

JSR 296 is going recommend a standard way to build a GUI framework. It hasn't been released as of this writing but whatever direction is chosen may be the best style to use in the future. Whether it is going to be appropriate for simple programs as well as full-strength programs remains to be seen.