Multiple main() methods in java

2019-02-03 09:16发布

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?

10条回答
forever°为你锁心
2楼-- · 2019-02-03 09:52

You can have only one main method in one class, But you can call one main method to the another explicitly

class Expmain
{
    public static void main(String[] ar)
    {
        System.out.println("main 1");
    }
}

class Expmain1
{
    public static void main(String[] ar)
    { 
        System.out.println("main 2");
        Expmain.main(ar);
    }
}
查看更多
Anthone
3楼-- · 2019-02-03 09:53

No, you can have any number of main-methods in a project. Since you specify which one you want to use when you launch the program it doesn't cause any conflicts.

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-03 09:59

This is perfectly fine. Having multiple main methods doesn't cause any problems. When you first start a Java program, execution begins in some function called main in a class specified by the user or by the .jar file. Once the program has started running, all the other functions called main are essentially ignored or treated like other functions.

查看更多
冷血范
5楼-- · 2019-02-03 10:00

It won't have an additional main-method, as main is static. So it's once per class.

If you have multiple main-methods in your project, you will specify which one to launch when starting your application.

查看更多
登录 后发表回答