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)".
NOTE: The return type of the method is not considered in the signature of a method.
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.
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.
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.
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
}
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:
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.
In this blog, you learned about methods in Java, including:
Enjoy learning, enjoy OOPS!
Subscribe to get well designed content on data structure and algorithms, machine learning, system design, object orientd programming and math.