Method Overloading in Java

Profile picture for user arilio666

Method overloading uses the same method name but with different parameters. It is also known as compile time polymorphism, static or early binding in Java.

In the Method overloading, the child argument gets the highest priority over than parent argument.

    public int add(int a, int b) {
        return a + b;
    }
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    public double add(double a, double b) {
        return a + b;
    }
    
  • We can see here we can access the methods with each parameter even though they are of the same name.

Benefits:

  1. It has a high potential to increase code readability.
  2. Provides flexibility to programmers.
  3. Cleaner code.
  4. Reduce execution time.
  5. Reduces complexity of code.
  6. Can reuse the code, which can save memory.

Code:

package week1.day2;
public class Calculator {
    public String concatenate(String str1, String str2) {
        return str1 + str2;
    }
    public int concatenate(int num1, int num2) {
        return Integer.parseInt(String.valueOf(num1) + String.valueOf(num2));
    }
    public String concatenate(String str, int num) {
        return str + num;
    }
    public String concatenate(int num, String str) {
        return String.valueOf(num) + str;
    }
    public static void main(String[] args) {
        Calculator cal = new Calculator();
        System.out.println(cal.concatenate(4, 3));
        System.out.println(cal.concatenate(55, "naruto"));
        System.out.println(cal.concatenate("uzu", 33));
        System.out.println(cal.concatenate("John", "Wick"));
    }
}
  • The first concatenate Method is called with two strings, the second concatenate Method is called with two integers, the third concatenate method is called with a string and an integer, and the fourth concatenate method is called with an integer and a string. 
  • Java selects the appropriate Method based on the number and types of arguments passed to the concatenate Method.
43
55naruto
uzu33
JohnWick
Tags