Friday, 3 November 2017

method overloading in java example

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, this is known as method overloading.

Method overloading increase the readability of the program. We can achieve method overloading either by changing the number of arguments or by changing the data type.

We will explain the method overloading by an example. This example achieve method overloading by changing the data type of argument.

Example 1:

package keywords;

public class Overloading {

       public int sum(int a, int b){

              return a+b;


       public double sum(double a, double b){

              return a+b;


       public static void main(String []p){

              Overloading obj=new Overloading();

              int c=obj.sum(10, 15);

              double k=obj.sum(15.5, 12.7);

              System.out.println("Sum of two integers is "+c);

              System.out.println("Sum of two double number is "+k);





Sum of two integers is 25

Sum of two double number is 28.2

Code Explanation:

In this example we have two method in a class complete with same name but these two methods have different type of parameters. When we call the sum method compiler identify the method by the type of parameters passed during the calling of method. When we call sum method with integers parameters then sum method with integer parameter is called, When we call with double parameter then it call method with double parameter. This thing we can observe in the output clearly