Search code examples
javamethodsprogram-entry-point

Multiple main() methods in java


I was wondering what the effect of creating extra main methods would do to your code.

For example,

public class TestClass {
    public static void main (String[] args){
        TestClass foo = new TestClass();
    }
}

After the program initially starts up, foo will be created and it would have another public main method inside it. Will that cause any errors?


Solution

  • It will cause no errors. Just because you initialize an object, doesn't mean the main method gets executed. Java will only initially call the main method of the class passed to it, like

    >java TestClass

    However, doing something like:

    public class TestClass
    {
     public static void main (String[] args)
     {
      TestClass foo = new TestClass();
      foo.main(args);
     }
    }
    

    Or

    public class TestClass
    {
     public TestClass()
     {
       //This gets executed when you create an instance of TestClass
       main(null);
     }
    
     public static void main (String[] args)
     {
      TestClass foo = new TestClass();
     }
    }
    

    That would cause a StackOverflowError, because you are explicitly calling TestClass's main method, which will then call the main method again, and again, and again, and....

    When in doubt, just test it out :-)