Method Overloading in java

Every class has one or more methods which are used to perform different functionalities in the application.

Can we have two methods having the same name in one class?

Yes, we can have two or more methods having the same name in one class, but the condition is their arguments list should be different.

What does it mean by different argument lists?

Argument lists can be different in the following ways.

  1. No. of parameters passed in the method
  2. Data type of parameters
  3. Sequence of data type of parameters

Let’s understand method overloading with examples.

1. Method overloading by changing the no. of arguments:

We have a class companyDetails which is having 2 methods with the same name company, but no. of arguments passed are different.

Output : Emp id is 1234
Emp id is 1234 and emp name is Shekhar

 

2. No. of arguments are same but datatypes of arguments are different:

We have one Addition class which is having 2 methods with the same name getSum. Both the methods have same no. of arguments (i.e. 2) , but their data types of arguments are different.

Output : 9
9.0

 

3. Sequence of data type of arguments is different:

We have a class StudentDetails which is having same name method called Student. Method Student have the same no. of arguments and dats types, but sequence of data type is different.

Output :
Student’s roll no and name :- 1234–Madhur
Student’s name and roll no :- Manan–6789

Note: Method Overloading is not possible by changing the return type of method.

The reason why Method Overloading is not possible by changing the return type of method?

If there will same methods with changed return data type, then there will be confusion which method to call. There you will get compile time error.

Is it possible to overload the main method?

Yes, it is possible to overload the main method. For more detail on main method Click here.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Aggregation in java
Method Overriding in Java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

2 Responses

  1. Priya says:

    In java method overloading means creating more than one method with same name but with different signature. It is very helpful blog , many thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *