Method Overloading in Java

In this tutorial, we will learn about Method Overloading in Java.

Method Overloading lets you define two or more methods with same name but different signatures where signature could differ by no. of input parameters or data type of input parameters or the sequence of the data type of input parameters. Overloading is one of the ways that Java supports polymorphism. Method overloading is also referred as Compile time Polymorphism or Static Polymorphishm.

Why to overload a method ?

You need method overloading when you want to perform the same operation for different inputs. For ex. you want to multiply 2,3 or 4 input parameters. If you want to multiply 2 integers then you create a method which accepts 2 integer parameters, for 3 integers you will create another method since method with 2 integer input parameters cannot be used for 3 input parameters and same is the case for 4 integers. Here you are doing the same operation with different input parameters. By overloading methods you don’t have to remember the different method names.

In java overloading of the methods can be done in following ways:

  • Method overloading by different no. of input parameters
  • Method overloading by different data types of input parameters
  • Method overloading by Sequence of data type of input parameters

Let’s see each method with an example:

Method overloading by different no. of input parameters:

This is the case when the method names are same but the no. of input parameters are different.

Check the output:

Method overloading by different data types of input parameters:

This is the case when the method names are same but the data types of input parameters are different.

Check the output:

Method overloading by Sequence of data type of input parameters:

This is the case when the method names are same but the sequence of data type of input parameters are different.

Check the output:

In the above examples, you might have observed that the return type of the overloading methods is same in some cases and different in other cases. This clearly indicates that the return type doesn’t matter in case of overloading.

Java has static methods, somebody might ask a question that can we overload static methods ? Why not. Let’s see with an example.

Overloading of static methods:

Check the output:

We have seen that we can overload static methods as well. Our main method is static. Now the question is can we overload main method ?

The answer is yes, we can overload main method as well.

Other Tutorials:

Related posts

Leave a Comment