Can we overload a main() method in Java?
Yes, you can.
The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded in a similar manner, JVM always looks for the method signature to launch the program.
The normal main method acts as an entry point for the JVM to start
the execution of program.
We can overload the main method in Java. But the program doesn’t
execute the overloaded main method when we run your program, we need
to call the overloaded main method from the actual main method only.
// A Java program with overloaded main()
import java.io.*;
public class Test {
// Normal main()
public static void main(String[] args) {
System.out.println("Hi Geek (from main)");
Test.main("Geek");
}
// Overloaded main methods
public static void main(String arg1) {
System.out.println("Hi, " + arg1);
Test.main("Dear Geek","My Geek");
}
public static void main(String arg1, String arg2) {
System.out.println("Hi, " + arg1 + ", " + arg2);
}
}
Yes,u can overload main method but the interpreter will always search for the correct main method syntax to begin the execution.. And yes u have to call the overloaded main method with the help of object.
class Sample{
public void main(int a,int b){
System.out.println("The value of a is " +a);
}
public static void main(String args[]){
System.out.println("We r in main method");
Sample obj=new Sample();
obj.main(5,4);
main(3);
}
public static void main(int c){
System.out.println("The value of c is" +c);
}
}
The output of the program is:
We r in main method
The value of a is 5
The value of c is 3