Can we overload a main()
method 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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With