Sum.java (method overloading) |
// Demonstration of the method overloading public class Sum { // Driver code public static void main( String args[ ] ) { Sum s = new Sum( ); if ( args.length == 3 ) System.out.println( s.sum( Integer.parseInt( args[0] ), Integer.parseInt( args[1] ), Integer.parseInt( args[2] ) ) ); else if ( args.length == 2 ) // See whether the number is a double by checking // whether it contains a period. if ( args[0].(".") || args[1].(".") ) System.out.println( s.sum( Double.parseDouble( args[0] ), Double.parseDouble( args[1] ) ) ); else System.out.println( s.sum( Integer.parseInt( args[0] ), Integer.parseInt( args[1] ) ) ); else System.out.println( "Error" ); } // Overloaded sum, which takes two int parameters public int sum( int x, int y ) { return x + y; } // Overloaded sum, which takes three int parameters public int sum( int x, int y, int z ) { return x + y + z; } // Overloaded sum, which takes two double parameters public double sum( double x, double y ) { return x + y; } } |
shell> java Sum
Output: Result: |