Multiple main() methods in java

后端 未结 10 642
忘了有多久
忘了有多久 2020-12-28 08:53

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

For example,

public class TestClass {
    public static void ma         


        
10条回答
  •  自闭症患者
    2020-12-28 09:21

    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 :-)

提交回复
热议问题