Method Overloading: Static Polymorphism in Java

Methods in Java

In Java, methods are used to perform specific tasks or operations with an object. The main() method is the first method executed by the compiler when a Java program is run.

The signature of a method consists of the method name and the parameter list. For example, the method "addition" performs an addition operation and may have a signature like "int addition(int a, int b)".

Example of methods in Java

NOTE: The return type of the method is not considered in the signature of a method.

What is method overloading?

In Java, method overloading allows us to have multiple methods with the same name in the same class, but with different argument lists. This is a form of polymorphism, specifically "static polymorphism", which allows us to perform a single task in different ways.

By using method overloading, we can create multiple versions of a method with different functionality based on the arguments passed to it. This allows for more concise and flexible code, as we can reuse the same method name for different purposes.

For example: Consider the addition method again, but this time you are not sure whether you will have to add three integers or two integers:

public class Calculator {
    // Method to add two integers
    public int addition(int a, int b) {
        return a + b;
    }
    
    // Method to add three integers
    public int addition(int a, int b, int c) {
        return a + b + c;
    }
}

In Java, method overloading is implemented by the compiler. When a method is called, the compiler checks the name and argument list (signature) of the method to determine which version of the method to call. If there are multiple methods with the same name but different argument lists, the compiler will choose the correct version of the method based on the arguments passed to it.

Calculator calc = new Calculator();
int sum1 = calc.addition(1, 2);    // calls the first version of the method
int sum2 = calc.addition(1, 2, 3); // calls the second version of the method

In the previous example, if we call calc.addition(1, 2), the compiler will look for a method with the name "addition" that takes two integers as arguments and returns an integer. It will find the first version of the "addition" method and call it with the given arguments.

Similarly, if we call calc.addition(1, 2, 3), the compiler will look for a method with the name "addition" that takes three integers as arguments and returns an integer. It will find the second version of the "addition" method and call it with the given arguments.

How to overload a method?

Each overloaded method must have a different argument list. This means that the number and/or types of arguments must be different between the overloaded methods. So there are three basic ways to create different argument lists:

Different number of arguments: This can be done by having one method take more or fewer arguments than the other.

public class Calculator {
    // Method to add two integers
    public int addition(int a, int b) {
        return a + b;
    }
    
    // Method to add three integers
    public int addition(int a, int b, int c) {
        return a + b + c;
    }
}

Different types of arguments: This can be done by having one method take different types of arguments than the other.

public class Calculator {
    // Method to add two integers
    public int addition(int a, int b) {
        return a + b;
    }
    
    // Method to add three integers
    public float addition(float a, float b, float c) {
        return a + b + c;
    }
}

Different order of arguments: This can be done by having one method take arguments in a different order than the other.

public class Calculator {
    // Method to add two integers
    public float addition(int a, float b) {
        return a + b;
    }
    
    // Method to add three integers
    public float addition(float a, int b) {
        return a + b + c;
    }
}

There are a few important points to consider when using overloaded methods in Java.

  • The return types of overloaded methods can be different as long as they have different argument lists. This means that we can have multiple methods with the same name but different return types, as long as they take different arguments.
  • Changing the return type alone is not sufficient to overload a method. The argument lists of the methods must also be different.
  • Static methods can be overloaded in the same way as non-static methods. However, if two methods only differ in being static or non-static and have the same signature, they are not considered overloaded methods.

In summary, method overloading allows us to have multiple methods with the same name within a class or subclass, as long as they have different argument lists. This allows us to reuse the same method name for different purposes, and makes our code more concise and flexible.

Why method overloading?

The main benefit of method overloading is improved code readability, as it allows for the use of a single name for similar tasks. For example, in the code below, multiple methods were used to perform various types of addition. However, each method had a different name, making the code less readable. By using method overloading, the same name could be used for all of the methods, improving the readability of the code and making it easier to understand.

int addTwo (int first , int second) {
    //Implementation code
}
int addThree (int first , int second , int third) {
    //Implementation code
}
String addStringNum (int first , String second) {
    //Implementation code
}

Type promotion and method overloading

Consider the following definition of work() method and call to work():

void work (long num) {
     System.out.println(num);
}
//...
//calling work() with an int value
int test = 0;
work (test);

This code can run without errors because the Java compiler automatically promotes the variable "test" to a higher data type. One can refer to this chart for type promotion in Java:

chart for type promotion in Java method overloading

Things get interesting when we consider type promotion in overloaded methods. Let’s see how? When a method is invoked, the Java compiler will first try to find an exact match based on the argument list. If it cannot find a match, it will attempt to promote the data type of the arguments to a higher type and check for a match again. This process will continue until a match is found or the promotion chain is completed.

If the promotion chain is completed without finding a match, the compiler will report a compile-time error. This is because the arguments cannot be promoted any further, and there is still no matching method available.

Example 1

public class TypePromo{

    public void Method(long first) {
        System.out.println("Long "+ first);
    }
    
    public void Method(float first) {
        System.out.println("Float "+ first);
    }
    
    
    public static void main(String args[]) {
        TypePromo obj = new TypePromo();
        obj.Method(21);
    }
}
//int gets promoted to long

Output: Long 21

Example 2: (Ambiguity error in method overloading)

public class TypePromo {

    public void Method(int first, double second) {
        System.out.println(first + second);
    }
    
    public void Method(double first, int second) {
        System.out.println(first + second);
    }
    
    
    public static void main(String args[]) {
        TypePromo obj = new TypePromo();
        obj.Method(14 , 14);
    }
}

This code results in a compilation error : The method Method (int, double) is ambiguous for the type TypePromo.This is because both types of Method() are applicable after type promotion which arises an ambiguity of which method to invoke. This is the ambiguity error.

Conclusion

In this blog, you learned about methods in Java, including:

  1. What methods are and their purpose
  2. The signature of a method
  3. Method overloading and its benefits
  4. Different ways to implement method overloading, along with examples
  5. How type promotion affects method overloading

Enjoy learning, enjoy OOPS!

Share Feedback

Coding Interview

Machine Learning

System Design

EnjoyAlgorithms Newsletter

Subscribe to get well designed content on data structure and algorithms, machine learning, system design, object orientd programming and math.

Explore More Content

Follow us on

©2023 Code Algorithms Pvt. Ltd.

All rights reserved.