Method Overloading In Java

- :  Method Overloading In Java : -

Defination of  Method Overloading :-

Method Overloading is a process of having multiple methods with the same name but difference in parameters.

OR In Other  Words :-

We can define Method Overloading as In a class having multiple methods with the same name but change in the Arguments is called as Method Overloading.


In order to achieve method overloading we have to satisfy one of the following three rules :-

  1. There should be a change in the number of arguments.(i.e length of the arguments).
  2. There should be a change in the datatype of  the arguments.
  3. There should be a change in the order or sequence of the datatype.



1) Method Overloading: changing no. of arguments 

In this example, We have created two classes the first one is Addition class and second one is TestNow Class(Main class). In Addition class we have two static methods by name add(), first add() method performs addition of two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods. 




OutPut :


2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.


 Here are some examples on method overloading.

Example 1 :
In this example, We have two classes, one is Student class and other one is Solution class (Main class, from where the program gets executed). In Student class we have four overloaded display methods. The first display method receives one integer argument, the second display method receives one String argument, the third display method receives one String and one integer argument and the final that is fourth display method receives one integer and one String argument. In the Solution class we have create the instance(Student s = new Student()) of Student class and we accessing the Student class members with the help of reference variable that is "s".





Example 2 :




Note
:-
 
  • In Java we can overload both static and non-static methods.
  • We can either have same return type or different return type during method overloading.
  • In Java we can overload even Main method but the execution will begin from the main method which accepts String[] args as it's parameter.


That's all for now folks! I hope I have explained it well. In case of any queries, just reach out to me by commenting below. 🙂

Take care, and I'll talk to you guys soon!

Peace.

No comments

Powered by Blogger.