What Is Method Overloading In Java?

Method Overloading
Many peoples get confused between method overloading and method overriding in java software development language. Earlier we learnt about method overriding in THIS POST. Method overloading concept is totally different than method overriding. If interviewer asks you question about method overloading then your answer should be like this "When class have two or more methods with same name but different parameters, it is called method overloading" in java software development language. Lets try to understand method overloading concept with example.

Method Overloading Example
We can achieve method overloading by changing number of arguments or by changing data types of arguments for same name methods in single class.

Method overloading by changing number of arguments
In bellow given example you can see that we have created two overloaded methods. 1st sum method will accept 2 arguments and 2nd sum method will accept 3 arguments to perform sum operation. This is called method overloading by changing number of arguments.

public class OverloadingByArgument {

 void Sum(int i, int j) {
  System.out.println(i + j);
 }

 void Sum(int i, int j, int k) {
  System.out.println(i + j + k);
 }

 public static void main(String args[]) {
  OverloadingByArgument ol = new OverloadingByArgument();
  ol.Sum(10, 10, 10); //It will call Sum(int i, int j, int k)
  ol.Sum(20, 20);//It will call Sum(int i, int j)
 }
}

OutPut
30
40

Method overloading by changing data types of arguments
You can also overload method by changing data types of argument. Here number of arguments can be same or different as per requirement. In bellow given example, Class have two sum methods with same number of arguments but different datatypes. 1st sum method will be called when you wants to sum two integer values and 2nd sum method will be called when you wants to sum two double values. You can use any other datatypes too.

public class OverloadingByDataTypes {

 void Sum(int i, int j) {
  System.out.println(i + j);
 }

 void Sum(double i, double j) {
  System.out.println(i + j);
 }

 public static void main(String args[]) {
  OverloadingByDataTypes ol = new OverloadingByDataTypes();
  ol.Sum(10.75, 10.5); //It will call Sum(double i, double j)
  ol.Sum(20, 20);//It will call Sum(int i, int j)
 }
}

OutPut
21.25
40


Advantage of Method Overloading
Using method overloading, We can create multiple methods with same name in same class to perform same action in different ways (using different number of arguments and it's datatypes). It will increases the readability of the software program. We can overload static methods too. view more java  software development language tutorials on THIS PAGE.

No comments:

Post a Comment