Introduction
This article describes a feature of the NetBeans IDE, the use multiple main classes in the same project. NetBeans provides this feature due to which we don't need to create another project everytime we create a main class. Normally when one starts learning the Java language, there are plenty of examples that must be compiled and must be executed to understand them, but the NetBeans IDE solves this problem by allowing multiple classes in the same project.
Multiple Main Classes
When we are working on a Java main class, let us say we are working with a simple main class that performs multiplication of 2 numbers. The code for this main class is as follows:
import java.io.*;
class Multiply
{
public static void main(String arg[])throws IOException
{
int a,b,c;
InputStreamReader br=new InputStreamReader(System.in);
BufferedReader bn=new BufferedReader(br);
System.out.println("enter one number");
a=Integer.parseInt(bn.readLine());
System.out.println("Enter the 2nd number");
b=Integer.parseInt(bn.readLine());
c=a*b;
System.out.println("multiplication of "+ a +" and "+ b +" is "+c);
}
}
The code above will be executed simply as we used to execute it. The screenshot is shown below.
Now if we want to try another piece of Java code then we have the following two choices:
-
either overwrite the code in the main class
-
since we are using the NetBeans IDE, we can put that code in another main class.
We will adopt the second option and demonstrate the use of multiple main classes in the same project of the NetBeans IDE.
A NetBeans project can accomodate more than one main class and it is easy to specify the main class an application can execute. This feature of the NetBeans IDE allows us to switch between a number of main classes within the same application or we can say, the same project. Then only the code in one of the main classes will be executed, making each class independent of the other class.
Adding another main class to the project
The following procedure adds another main class to a project in the NetBeans IDE:
-
Right-click on the project name on the very left panel and click on the "New" menu item in the popup menu that appears, as in the following:
-
A window named "New Java Class" will be shown, provide the name of your class and choose a project for the class.
-
Now click "Finish" to create the class. Note that the class template is displayed in the NetBeans workspace.
Now one can add and execute the other main class in the same project. To change the main class presently in use, just use the following procedure:
-
Go to the file menu and select "Project Properties"
-
A dialog with all the options will be shown, click on the "Run" menu.
-
On this page set the "Main class" option to your main class that you want to execute by clicking on the "Browse" button.
-
Now click on the "Ok" button.
-
And now you can execute the code.