Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we overload the main method in Java?

Tags:

java

Can we overload a main() method in Java?

like image 554
Mohan Avatar asked Sep 21 '10 10:09

Mohan


People also ask

What happens if we overload the main in Java?

Overloading the main method Yes, we can overload the main method in Java, i.e. we can write more than one public static void main() method by changing the arguments. If we do so, the program gets compiled without compilation errors.

Can you overload override a main method?

In short, the main method can be overloaded but cannot be overridden in Java. That's all about overloading and overriding the main method in Java. Now you know that it's possible to overload main in Java but it's not possible to override it, simply because it's a static method.


1 Answers

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) 
like image 115
Jon Skeet Avatar answered Sep 21 '22 18:09

Jon Skeet