Can we overload the main method in Java?

后端 未结 14 1879
不知归路
不知归路 2020-11-30 18:07

Can we overload a main() method in Java?

14条回答
  •  醉话见心
    2020-11-30 18:33

    You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM. For example:

    public class Test {
        public static void main(String[] args) {
            System.out.println("main(String[] args)");
        }
    
        public static void main(String arg1) {
            System.out.println("main(String arg1)");
        }
    
        public static void main(String arg1, String arg2) {
            System.out.println("main(String arg1, String arg2)");
        }
    }
    

    That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.

    You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

    EDIT: Note that you can use a varargs signature, as that's equivalent from a JVM standpoint:

    public static void main(String... args)
    

提交回复
热议问题