Can there exist two main methods in a Java program

2019-01-16 19:11发布

Can there exist two main methods in a Java program? Only by the difference in their arguments like:

public static void main(String[] args)

and second can be

public static void main(StringSecond[] args)

If it is possible,which Method will be used as the entry point? How to identify this? please help.

16条回答
孤傲高冷的网名
2楼-- · 2019-01-16 20:12

the possibility of two main(String[] args) methods within the same scope create confusion for the JVM. It fails to use them as overloaded methods. So the signatures in terms of parameters) must be different.

查看更多
Fickle 薄情
3楼-- · 2019-01-16 20:13

The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing

2<SPACE>

As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))

public class Locomotive {
    Locomotive() { main("hi");}

    public static void main(String[] args) {
        System.out.print("2 ");
    }

    public static void main(String args) {
        System.out.print("3 " + args);
    }
}
查看更多
Evening l夕情丶
4楼-- · 2019-01-16 20:14

Only public static void main(String[] args) counts. This is the only signature considered to be the true main() (as the program entry point, I mean).

查看更多
\"骚年 ilove
5楼-- · 2019-01-16 20:14

In Java, you can have just one public static void main(String[] args) per class. Which mean, if your program has multiple classes, each class can have public static void main(String[] args). See JLS for details.

查看更多
登录 后发表回答