Methods Overloading in Java

In Java we can define more than one method with same name but different parameters which called method overloading.Method overloading increase readability of program.

Lets take an example where we need to find addition of given numbers.Number can be two or three then we can use method overloading feature there.Overloading can be done by following two ways.

  • By changing the number of parameters/arguments
  • By changing the data type

Example of Method Overloading

Here Calculate has three methods to find sum of two integers,two doubles and three integers.

public class Calculate {

public void sum(int a,int b){
 int c = a+b;
 System.out.println("Sum of two integers:"+c);
}
public void sum(double a,double b){
 double c = a+b;
 System.out.println("Sum of two doubles:"+c);
}
public void sum(int a,int b,int c){
 int sum = a+b+c;
 System.out.println("Sum of three integers:"+sum);
}
public static void main(String args[]){

 Calculate c = new Calculate();
 c.sum(10, 20);
 c.sum(10.5, 20.6);
 c.sum(10, 20,30);
}
}

Output

Sum of two integers:30
Sum of two doubles:31.1
Sum of three integers:60

Leave a Reply