Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of multiple main methods?

Tags:

c#

c# enables us to define more than one class with the method. Main method is the entry point for program execution. So why do we want to have more than one place for program execution. What is the advantage of multiple main methods over single main method.

Edit:

Example.cs

Class Example_1
{
 public static void Main()
  {
   System.Console.WriteLine("Example 1")
  }

 public void test()
  {
   System.Console.WriteLine("Test method")
  }
}

Class Example_2
{
 public static void Main()
  {
   System.Console.WriteLine("Example 2")
  }
}

If I type "csc Example.cs" then what would happen ? What to do if I want to inherit test method of Class Example_1 in Class Example_2. Will this code work.

Example_1 abc = new Example_1();
abc.test();
like image 631
subanki Avatar asked Jan 16 '11 09:01

subanki


People also ask

Can we use multiple main method?

From the above program, we can say that Java can have multiple main methods but with the concept of overloading. There should be only one main method with parameter as string[ ] arg.

Can we use multiple main methods in same class?

Yes, we can define multiple methods in a class with the same name but with different types of parameters.

What is the purpose of the main method?

In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method. If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.

What if there are 2 main methods in Java?

Yes, you can have as many main methods as you like. You can have main methods with different signatures from main(String[]) which is called overloading, and the JVM will ignore those main methods.


1 Answers

You could use it so that different build configurations built the same executable but with different entry points - for example a console entry point vs a WinForms entry point.

Personally I use it when giving talks and in the sample code for C# in Depth. Each file is a self-contained example, but it's simpler to just have one entry point - so that entry point uses a utility class to prompt the user for which example they want to run.

like image 85
Jon Skeet Avatar answered Sep 24 '22 22:09

Jon Skeet