Method Overloading in Java

In this tutorial, we will learn about Method Overloading in Java. When we create more than methods in a class with the same name it is known as Method Overloading in Java. The main motive behind this concept is to keep code more readable and easy.

Some rules to perform method overloading in Java.

  • Name of the method must be the same.
  • Arguments must be changed (In count or type)
  • Can change return type.
  • Can change access modifier.

Next, we will try to understand this concept with the help of an example. In Example, we will create a class called Calculator and we will create three add methods in this class(Mean we will overload add method).

Example Program:

class Calculator{
  public int add(int x,int y){
    return x+y;
  }
  public int add(int x,int x,int z){
    return x+y+z;
  }
  public double add(double x,double y){
    return x+y;
  }
  
  public static void main(String args[]){
    Calculator obj=new Calculator();
    System.out.println(obj.add(10,12));
    System.out.println(obj.add(10,12,15));
    System.out.println(obj.add(10.5,20.6));
  }
}

In the above example, you can see we have created three add methods in Calculator class and each with different arguments(number or data type-wise) and with the same name. After that when we called them there is no confusion we are just calling add method and it automatically invokes to an appropriate method according to too actual arguments.

Wait have you ever noticed. It doesn’t method what type(primary data types) of value in print or println method they always show output. How this is possible. Simple because they are overloaded in PrintStream class. Click here to check.

Spread the love
Scroll to Top