Method Overloading (Cont.): The main Method


Overloading the main Method
The following program shows we can overload the main method, but JVM only calls the main method which receives string array as arguments. It also shows we can have two or more static methods with same name, but differences in input parameters. However, we cannot overload two methods if they differ only by static keyword (number of parameters and types of parameters are the same).

OverloadMain.java (overloading the main method)
// A Java program with overloaded main( ) 
public class OverloadMain { 
  // Normal main( ) 
  public static void main( String[ ] args ) { 
    if      ( args.length == 1 )  OverloadMain.main( args[0] );
    else if ( args.length == 2 )  OverloadMain.main( args[0], args[1] ); 
  } 
  // Overloaded main methods 
  public static void main( String arg1 ) { 
    System.out.print ( arg1 + " "  ); 
    OverloadMain.main( arg1, "two" ); 
  } 
  public static void main( String arg1, String arg2 ) { 
    System.out.print( arg1 + " " + arg2 ); 
  } 
}
shell> java OverloadMain    

Output:             Result:

No Overloading the Operators
Unlike C++, Java doesn’t allow user-defined overloaded operators. Internally, Java overloads operators; for example, + is overloaded for concatenation.




      Doctor: “I’m sorry but you suffer from a terminal illness and have only ten to live.”    
      Patient: “What do you mean, ten? Ten what? Months? Weeks?!”    
      Doctor: “Nine.”