What is overloading? What happens if we overload a main method in java?

Java 8Object Oriented ProgrammingProgramming

Overloading is one of the mechanisms to achieve polymorphism. If a class contains two methods with the same name and different parameters, whenever you call this method the method body will be bound with the method call based on the parameters.

Example

In the following Java program, the Calculator class has two methods with name addition. The only difference between them is that one contains 3 parameters and the other contains 2 parameters.

Here, we can call the addition method by passing two integers or three integers. Based on the number of integer values we pass, the respective method will be executed.

 Live Demo

public class Calculator {
   public int addition(int a , int b){
      int result = a+b;
      return result;
   }
   public int addition(int a , int b, int c){
      int result = a+b+c;
      return result;
   }
   public static void main(String args[]){
      Calculator cal = new Calculator();
      System.out.println(cal.addition(12, 13, 15));
   }
}

Output

40

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.

But, when we execute this program JVM searches for the main method which is public, static, with return type void, and a String array as an argument and calls it. It never calls main methods with other types as arguments.

public static int main(String[] args){
}

Note − If such method is not found, a run time error is generated.

Example

In the following example, we are trying to overload the public static void main() method (by having two main methods with different parameters), one accepts a String array as an argument and the other which accepts an integer array as argument −

 Live Demo

public class OverloadingMain {
   public static void main(String args[]) {
      System.out.println("main method with String array as arguments");
   }
   public static void main(int args[]) {
      System.out.println("main method with integer array as arguments");
   }
}

Output

When we execute this program the main method with integer array as argument is never called.

main method with String array as arguments
raja
Published on 03-Jul-2019 12:23:59
Advertisements