Website For Developers

Method Overloading in Java



For Example

int sum (int , int)
int sum (double , double)


Example with the different types of parameters

class ParametersDifferenttype {

   public static void main(String args[]) {
     sumfactory(1,2);
     sumfactory(1.4 , 2.5);
   }

   public static void sumfactory (int a, int b) {
     int c = a+b;
     System.out.println( "Sumfactory Method with integer type parameters." );
     System.out.println( "And total is : " +c);
   }

   public static void sumfactory (double a, double b){
     double c = a+b;
     System.out.println( "Sumfactory Method with double type parameters." );
     System.out.println( "And total is : " +c);
   }
}

Output

Sumfactory Method with integer type parameters.
And total is : 3
Sumfactory Method with double type parameters.
And total is : 3.9


Example with the different number of parameters

class ParametersDifferentnum {

   public static void main(String args[]) {
    sumfactory(3, 6);
    sumfactory(2, 5, 9);
   }

   public static void sumfactory (int a, int b) {
     int c = a+b;
     System.out.println( "Sumfactory Method with two integer parameters." );
     System.out.println( "And total is : " +c+ "\n");
   }

   public static void sumfactory (int a, int b, int c) {
     int d = a+b+c;
     System.out.println( "Sumfactory Method with three integer parameters." );
     System.out.println( "And total is : "+d);
   }
}

Output

Sumfactory Method with two integer parameters.
And total is : 9

Sumfactory Method with three integer parameters.
And total is : 16