Method Overloading in Java | Example Program

When a class has more than one method having the same name but with different parameter lists, this feature is called method overloading in Java.

In other words, when multiple methods are declared with the same name but with different method signatures, all these methods are said to be overloaded methods. This process is referred to as method overloading.

Let’s understand this feature with the help of a realtime example.

Suppose you have a vehicle. When you apply a brake in a vehicle, it stops the vehicle. The method brake() represents the behavior of stopping the vehicle.

The car brake is applied by the leg and the cycle brake is applied by hand. The way of operating is different but the desired behavior is one and the same.

Similarly, we can define multiple methods with the same name in a class. If the behavior of more than one method with the same name does the same thing on varying numbers of parameters or varying types of parameters, it is called overloading in java.

Overloading is one of the ways that Java implements polymorphism. It is a powerful and very useful feature for increasing the maintainability and readability of code.

How Java compiler differentiate overloaded methods?


Java compiler differentiates overloaded methods by their signatures. The signature of a method is defined by its name and list of parameters.

The return type of a method is not part of the method signature. It does not play any role in resolving methods overloaded.

Look at the below figure to understand the instance method signature.

Method overloading in Java

When a class has multiple methods having the same name with the different parameter list, the compiler differentiates one method from another method by checking the different number of parameters or types of passed parameters.

Therefore, it should be used with caution because java compiler does not consider the return type while differentiating the overloaded method.

Method overloading rules in Java


Here is the list of rules by which method overloading can be implemented in Java. They are as follows:

1. The method name must be the same.

2. Parameters must be different i.e each overloaded method must take a unique list of parameter types. The parameters can be changed in one of the following three ways.

a. Data types of Parameters

For example:

void add(int a, int b); // There are two parameters a and b with data type int.
void add(int a, float b); // Here, two parameters a, and b with data type int and float. The data type is different in both cases.

This is a valid case of method overloading. If we call the method add(10, 20) by passing argument values, JVM invokes the first method. If we invoke add(10, 20.5f), JVM executes the second method.

b. Number of Parameters

For example:

void sum(int a, int b); // Two parameters a and b with data type int.
void sum(int a, int b, int c); // Three parameters a, b, and c with data type int. Here, the number of parameters is different but the data type is the same.

This is also a valid case because there is a difference in the number of parameters passed to methods.

c. Sequence of Data type of Parameters

For example:

void sub(int a, double b);
void sub(double a, float a);

Here, the sequence of data type of parameters is different. So, this is a valid case of method overloading.

3. Access modifiers can be anything or different.
4. Return type can be anything or different.
5. Exception thrown can be anything.
6. The implementation does not matter in this case. A method can have any kind of logic.

Which (Java compiler or JVM) decides which overloaded method to invoke?


Only JVM decides at runtime (dynamically) which overloaded method is to be executed because methods are called by using object. The creation of an object takes place at runtime by JVM.

Therefore, JVM decides which overloaded method is to be called at runtime. Java compiler does not decide which overloaded method is actually called by the user at the time of compilation.

How JVM recognizes which overloaded method is called?


When multiple methods are defined with the same name in a class then JVM observes the signature of methods. Method signature consists of method name along with its method parameters.

If the two methods have the same name then their method signatures will definitely different. For example, two human beings can have the same name but their signatures will definitely different.


On the basis of method signatures, JVM understands both methods are different and decides which appropriate method is to be called.

Features of Method overloading


There are the following features of method overloading in java which you should have to keep in mind.

1. The call to overloaded method is bonded at compile time.

2. The concept of method overloading is also known as compile-time polymorphism in java.

3. Method overloading is generally done in the same class. But it can also be done in the subclass. You will have to make a relationship between the parent class and child class by using extends keyword for it.

4. Method overloading in Java cannot be done by changing the return type of the method because there may occur ambiguity. But the overloaded methods can change the return type.

5. The private methods can be overloaded in Java.

6. The final methods can be overloaded in Java.

7. The main method can also be overloaded in Java.

8. Both static and instance methods can be overloaded in Java. Method overloading is possible when two or more static methods with the same name, but the difference in the list of parameters.

When to use Method overloading in Java


Method overloading is a powerful feature in Java but should be used as per needs. It should be used when you actually need multiple methods with different parameters but methods do the same thing.

If multiple methods perform different tasks, don’t use the method overloading concept. Method overloading is done in java due to the following needs:

  • Method overloading is done to reuse the same method name.
  • It is done to make the program logically more readable and understandable.
  • It is used to achieve the compile-time polymorphism in Java.

Java Method overloading Example Program


Let’s take some important example programs based on Java method overloading concepts.

1. Method overloading by changing number of arguments

Let’s take an example program where we will create two methods, the first method sum() will perform addition of two numbers and second method sum() will perform addition of three numbers by overloading concept. Look at source code to understand better.

Program source code 1:

package methodOverloading; 
public class Addition 
{ 
// Method to calculate the sum of two numbers. 
// Declare an instance method sum with two parameters a and b having data type int. 
   void sum(int a, int b) 
   { 
     int s = a + b; 
     System.out.println("Sum of two numbers: " +s); 
   } 
// Method to calculate sum of three numbers. 
// Declare an instance method sum with three parameters a,b, and c having data type int. 
// Here, the method sum() is overloaded having the same method name. 

   void sum(int a, int b, int c) 
   { 
     int t = a + b + c; 
     System.out.println("Sum of three numbers: " +t); 
   } 
public static void main(String[] args) 
{ 
   Addition a = new Addition(); 
    a.sum(10, 20); // It will call sum() method to calculate sum of two arguments. 
    a.sum(50, 100, 200); // It will call sum() method to calculate sum of three arguments. 
  } 
 }
Output: 
       Sum of two numbers: 30 
       Sum of three numbers: 350

As you can see in the above program, the method sum() is overloaded based on the number of parameters. We have declared two methods having the same name but the different number of parameters.

The overloaded methods have calculated the sum of two numbers and three numbers based on the passing of arguments while calling method at runtime by JVM.

2. Method overloading by changing data type of parameters

Let’s create a program where we will create two methods having the same name but will differ in the data type of parameters.

The first method sub() will receive two integer arguments and the second method sub() will receive two double arguments. Look at the source code of program.

Program source code 2:

package methodoverload; 
public class Subtraction 
{ 
// Declare an instance method sub with two parameters x and y having data type int. 
   int sub( int x, int y) 
   { 
      int a = x - y; 
      System.out.println("Subtraction of two numbers: " +a); 
      return a; 
    } 
// Declare an instance method sub with two parameters x and y having data type double. 
   double sub(double x, double y) 
   { 
     double b = x - y; 
     System.out.println("Subtraction of two numbers: " +b); 
     return b; 
   } 
public static void main(String[] args) 
{ 
   Subtraction s = new Subtraction(); 
    s.sub(6, 5); // It will call the method sub() to calculate the subtraction of two int type arguments. 
    s.sub(20.8, 10.9); // It will call the method sub() to calculate the subtraction of two double type arguments. 
  } 
}
Output: 
       Subtraction of two numbers: 1 
       Subtraction of two numbers: 9.9

In the above program, method sub() is overloaded based on data types of parameters. We have declared two methods having the same name but different data types of parameters.

The overloaded methods have calculated subtraction of two numbers based on data type of parameters.

3. Method overloading by changing sequence of data type of parameters

Let’s take an example program where we will overload methods by changing sequence of data type of parameters.

Program source code 3:

package methodOverloading; 
public class Multiplication 
{ 
  void multiply(int a, double b) 
  { 
    double m1 = a * b; 
    System.out.println("Multiplication of two numbers: " +m1); 
  } 
void multiply(double a, int b) 
{ 
  double m2 = a * b; 
  System.out.println("Multiplication of two numbers: " +m2); 
 } 
public static void main(String[] args) 
{ 
   Multiplication m = new Multiplication(); 
   m.multiply(10, 20.5); // It will call method multiply() to calculate the multiplication of two arguments int and double. 
   m.multiply(10.5, 30); // It will call method multiply() to calculate the multiplication of two arguments double and int. 
  } 
}
Output: 
       Multiplication of two numbers: 205.0 
       Multiplication of two numbers: 315.0

In the above program, the method multiply() is overloaded based on the sequence of data type of parameters. The overloaded methods have calculated multiplication of two numbers based on the sequence of argument types while calling methods at runtime by JVM.

Java Method overloading done in Subclass


Let’s create a program where method overloading will be done in the child class or subclass. We will make a relationship between the parent class and child class by using extends keyword.

We will create one method msg() in the parent class and second method msg() in the child class or subclass. While calling from the class ‘Test’, the msg() will receive int argument and double argument.

Program source code 4:

package methodOverloading; 
public class SuperClass 
{ 
  void msg(int x, int y) 
  { 
    System.out.println("Hello Java"); 
  } 
 } 
public class Subclass extends SuperClass 
{ 
  void msg(double x, double y) 
  { 
    System.out.println("Welcome you in Java programming"); 
  } 
} 
public class Test 
{ 
  public static void main(String[] args) 
  { 
    Subclass sc = new Subclass(); 
     sc.msg(10, 20); 
     sc.msg(2.5, 3); 
   } 
 }
Output: 
       Hello Java 
       Welcome you in Java programming

Why method overloading is not possible by changing return type of method?


In Java, Method overloading cannot be done when the return type, method name, and argument list are the same because there may occur ambiguity. Let’s see in the program how ambiguity may occur:

Program source code 5:

package methodOverloading; 
public class ReturnTypeEx1 
{ 
  public int m1(int a, int b) // Duplicate method error. 
  { 
    int x = a + b; 
    return x; 
   } 
 public int m1(int c, int d) // Duplicate method error. 
 { 
   int y = c * d; 
    return y; 
  } 
 } 
public class ReturntypeTest 
{ 
 public static void main(String[] args) 
 { 
   ReturnTypeEx1 obj = new ReturnTypeEx1(); 
   int sum = obj.m1(20, 30); 
   System.out.println(sum); 

   int multiply = obj.m1(20,30); 
   System.out.println(multiply); 
  } 
}
Output: 
        50

As you can see in the output of program, method overloading cannot be done because the compiler shows the duplicate method error.

Let’s take another example program where we will keep return type different, method name, and argument list the same.

Program source code 6: 

package methodOverloading; 
public class ReturnTypeEx1 
{ 
  public int m1(int a, int b) // Return type is int. 
  { 
    int x = a + b; 
     return x; 
   } 
 public double m1(int c, int d) // Return type is double. 
 { 
   int y = c * d; 
    return y; 
  } 
 } 
public class ReturntypeTest 
{ 
  public static void main(String[] args) 
  { 
    ReturnTypeEx1 obj = new ReturnTypeEx1(); 
    int sum = obj.m1(20, 30); 
    System.out.println(sum); 

    int multiply = obj.m1(20,30); 
    System.out.println(multiply); 
   } 
 }
Output: 
        50

The compiler again shows the duplicate method error because the compiler checks only method signature for duplication, not the return type.

Therefore, method overloading is not possible even though their return type is different. So, the return type does not play any role in the case of method overloading.

Can we overload main() method in Java?


Yes, we can overload the main() method in Java. A class can have any number of main() methods but JVM calls that main() method that receives string array as an argument only.

Therefore, the execution always starts from public static void main(String[] args) only. Let’s understand this concept better by taking an example program based on main method.

Program source code 7: 

public class MainMethodOverloadingTest 
{ 
 public static void main(String[] args) 
 { 
   System.out.println("main(String[] args)"); 
    main(); 
 } 
public static void main() 
{ 
   System.out.println("main without args"); 
 } 
public static void main(String args) 
{ 
   System.out.println("main with string args"); 
 } 
}
Output: 
       main(String[] args) main without args

Valid/Invalid cases of Method overloading in Java


Let’ see a few cases of the valid or invalid case of method overloading in Java.

Case 1:

void sum(int a, int b, float c)
void sum(int c, int d, float e)

Result: Compile-time error. Here, the argument lists are exactly the same. Both methods are having the same number of parameters, and the same sequence of data types of the parameters.

Case 2:

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

Result: Perfectly fine. This is a valid case of method overloading. This is because data types of arguments are different.

Case 3:

void msg(String a, char c)
void msg(char x)

Result: Perfectly fine. A valid case of method overloading. Here, the number of parameters is different.

Case 4:

void msg()
void msg(char x)

Result: This is a valid case of method overloading. This is because the number of parameters is different. There is no parameter in the first method and the second method has one parameter.

Case 5:

void msg(Object o, char a)
void msg(char x, Object o)

Result: This is a valid case of method overloading. This is because the sequence of data types of parameters is different. The first method is having (Object, char)and the second method has (char, Object).

Case 6:

Object msg(String s)
String msg(String a)

Result: Duplicate method error. Argument lists are the same. Even though return type of methods is different. Still, it is an invalid case of method overloading. The return type of method does not play any role while overloading a method.

Q. Identify the error in the following code.

public class Test {
public static void m1(int a) {
	
}
public static int m1(int y){
   return y;
}

Ans: Duplicate method error by the compiler.

Advantage of Method overloading in Java


The advantages of method overloading in Java are as follows:

  1. In Java, Method overloading provides the same method name to reuse in the program.
  2. It increases the readability and understanding of the program.
  3. It makes the program logically more readable and understandable.
  4. It helps in achieving the compile-time polymorphism.
  5. It is useful to avoid repeating same code in different methods.

Hope that this tutorial has covered the basic points of method overloading in Java with example programs. I hope that you will have understood this topic and enjoyed it.
Thanks for reading!!!! Next ⇒ Use of method overloading in realtime java project⇐ PrevNext ⇒

Leave a Comment