Method Overloading in Java

Hello Coders, today we will see how to overload methods in Java. But before that let’s see what actually is method overloading and then we will see the example in Java language.

Method Overloading

Method Overloading is having two or more methods in a class with the same name but a different number of parameters or a different data type.

Example:

int sum(int a,int b)

int sum(int a)

int sum(int a,int b,int c)

int sum(double a,double b)

When calling the method the appropriate method will get identified according to the parameters passed and their data type.

Let’s look at how to program in Java for method overloading below:

class codespeedy
{
  int sum(int a,int b)
  {
    return a+b;
  }
  int sum(int a)
  {
    return a+100;
  }
  int sum(int a, int b, int c)
  {
    return a+b+c;
  }
}

public class test
{ 
    public static void main(String args[]) 
    { 
        codespeedy cs=new codespeedy();
        int res=cs.sum(10,20);
        System.out.println("Result is "+res);
        res=cs.sum(20);
        System.out.println("Result is "+res);
        res=cs.sum(10,20,30);
        System.out.println("Result is "+res);
        
    } 
}

As you can see I have made three different calls to the method sum, each time a different method triggers and then return a value.

Let’s see it in the output below:

Result is 30
Result is 120
Result is 60

 

Also Read:

Leave a Reply

Your email address will not be published.