Method Overloading in Java

Table of Contents

Method Overloading in Java

There are certain situations while programming and the programmer are bound to use the same name of the method but to do this may lead to ambiguity.

What is Method Overloading?

When a class, contains multiple methods of the same name and calling them with respect to the parameters of it, is known as Method Overloading.

But it doesn’t mean that each and everyone will be the same. To make it distinguishable, we are left with two options which are:

  • With changing the Datatypes of it
  • With changing in the number of arguments accepted by it

Now, see both of them with separate examples.

By Changing the Datatypes of it

class Sample
{  
  int add(int a,int b)
  {
    return a+b;
  }  
  double add(double a,double b)
  {
    return a+b;
  }  
  public static void main(String[] args)
  {  
   Sample obj = new Sample();
   System.out.println(obj.add(1,2));  
   System.out.println(obj.add(1.2,2.3));  
  }
} 

In the above example, you can notice the names of the methods are the same. Despite being the same in name, they performed the method overloading perfectly and this is because of the datatypes accepted by them.

The above method accepts integer type of data, while the method below it accepts the double datatype which helps the compiler to distinguish between both of the methods during compile time only.

By Changing the no. of arguments accepted.

class Sample
{  
  int add(int a,int b)
  {
    return a+b;
  }  
  int add(int a,int b,int c)
  {
    return a+b+c;
  }  
  public static void main(String[] args)
  {  
   Sample obj = new Sample();
   System.out.println(obj.add(1,2));  
   System.out.println(obj.add(1,2,3));  
  }
}  

In the above example, the name of the methods are the same but while calling them, it doesn’t put the ambiguity problem in front of the compiler . This is because, despite the same name of the methods, both the methods accept a different number of arguments and this helps the compiler to distinguish between them easily.

Leave a Reply