Java Method Overloading: Definition and Examples
Table of Content:
What is Method Overloading
In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
Method overloading is one of the ways that Java supports polymorphism.
Problem without method overloading
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as addition(int,int)
for two parameters, and additionMethod(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
- The main advantage of this is cleanliness of code.
- Method overloading increases the readability of the program.
- Flexibility
- Overloaded methods give programmers the flexibility to call a similar method for different types of data. If you are working on a mathematics program, for example, you could use overloading to create several multiply classes, each of which multiplies a different number of type of argument: the simplest
multiply(int a, int b)
multiplies two integers; the more complicated methodmultiply(double a, int b, int c)
multiplies one double by two integers -- you could then call "multiply" on any combination of variables that you created an overloaded method for and receive the proper result.
Different ways to overload the method
There are two ways to overload the method in java
- By changing number of arguments
- By changing the data type
Method Overloading: changing no. of arguments
In this example, we have created two methods, first addition()
method performs
addition of two numbers and second addition()
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.
class OverloadingExample{ public static void main(String[] args){ System.out.println(AdderClass.addition(12,11)); System.out.println(AdderClass.addition(11,15,13)); } } class AdderClass{ static int addition(int a,int b){return a+b;} static int addition(int a,int b,int c){return a+b+c;} }
Output
23 39 Press any key to continue . . .
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
addition(int a, int a)
first receives two integer arguments and second add
method addition(double a, double b)
first receives two double arguments, then it calculate.
In this example, we are creating static methods so that we don't need to create instance for calling methods.
class OverloadingExample{ public static void main(String[] args){ System.out.println(AdderClass.addition(11,12)); System.out.println(AdderClass.addition(11.3,15.6)); } } class AdderClass{ static int addition(int a, int b){ return a+b; } static double addition(double a, double b){ return a+b; } }
Output
23 26.9 Press any key to continue . . .
Method Overloading: changing data type of arguments
As you can see, method( ) is overloaded four times. The first version takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth takes one double parameter. The fact that the fourth version of method( ) also returns a value is of no consequence relative to overloading, since return types do not play a role in overload resolution.
// Demonstrate method overloading. class OverloadDemo { void method() { System.out.println("No parameters"); } // Overload test for one integer parameter. void method(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void method(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double method(double a) { System.out.println("double a: " + a); return a*a; } } class OverloadExample { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.method(); ob.method(10); ob.method(10, 20); result = ob.method(123.25); System.out.println("Result of ob.test(123.25): " + result); } }
Output
No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625 Press any key to continue . . .
Method Overloading: changing data type of arguments. Example find maximum value from two number
Let’s consider the example discussed earlier chapter for finding maximum numbers of integer type.
If, let’s say we want to find the maximum number of double type. Then the concept of overloading will
be introduced to create two or more methods with the same name but different parameters.
The following example explains the same ?
public class ExampleOverloading { public static void main(String[] args) { int a = 12; int b = 6; double c = 10.3; double d = 5.4; int result1 = maxFunction(a, b); // same function name with different parameters double result2 = maxFunction(c, d); System.out.println("Maximum Value = " + result1); System.out.println("Maximum Value = " + result2); } // for integer public static int maxFunction(int n1, int n2) { int max; if (n1 > n2) max = n1; else max = n2; return max; } // for double public static double maxFunction(double n1, double n2) { double max; if (n1 > n2) max = n1; else max = n2; return max; } }
Output
Maximum Value = 12 Maximum Value = 10.3 Press any key to continue . . .
Java’s automatic type conversions can play a role in overloading Method
When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method’s parameters. However, this match need not always be exact.
// Automatic type conversions apply to overloading. class OverloadExample { void testMethod() { System.out.println("No parameters"); } // Overload test for two integer parameters. void testMethod(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter void testMethod(double a) { System.out.println("Inside test(double) a: " + a); } } class Overload { public static void main(String args[]) { OverloadExample obj = new OverloadExample(); int p = 57; obj.testMethod(); obj.testMethod(5, 10); obj.testMethod(p); // this will invoke test(double) obj.testMethod(158.6); // this will invoke test(double) } }
Output
No parameters a and b: 5 10 Inside test(double) a: 57.0 Inside test(double) a: 158.6 Press any key to continue . . .
As you can see, this version of OverloadExample does not define testMethod(int)
.
Therefore, when testMethod( )
is called with an integer argument inside Overload, no matching method is found.
However, Java can automatically convert an integer into a double, and this conversion can
be used to resolve the call. Therefore, after testMethod(int)
is not found, Java elevates p to double
and then calls testMethod(double)
. Of course, if testMethod(int)
had been defined,
it would have been called instead. Java will employ its automatic type conversions only if no exact match is found.
Method Overloading with Type Promotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingAutoCast{ void division(int a,int b){ System.out.println("int arg method invoked: Ans: "+(a/b)); } void division(long a,long b){ System.out.println("long arg method invoked: Ans: "+(a/b)); } public static void main(String args[]){ OverloadingAutoCast obj=new OverloadingAutoCast(); obj.division(20,5);//now int arg sum() method gets invoked } }
Output:
int arg method invoked: Ans: 4 Press any key to continue . . .
Method Overloading with Type Promotion in case of ambiguity
If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.
class OverloadingAutoCast{ void division(long a,int b){ System.out.println("int arg method invoked: Ans: "+(a/b)); } void division(int a,long b){ System.out.println("long arg method invoked: Ans: "+(a/b)); } public static void main(String args[]){ OverloadingAutoCast obj=new OverloadingAutoCast(); obj.division(20,5);//now int arg sum() method gets invoked } }
Output:
OverloadingAutoCast.java:14: error: reference to division is ambiguous obj.division(20,5);//now int arg sum() method gets invoked ^ both method division(long,int) in OverloadingAutoCast and method division(int,long) in OverloadingAutoCast match 1 error
Why Method Overloading is not possible by changing the return type of method only?
Method overloading is not possible by changing the return type of the method only because of ambiguity.
class AdderClass{ static int addme(int a,int b){ return a+b; } static double addme(int a,int b){ return a+b; } } class OverloadingSampleTest{ public static void main(String[] args){ System.out.println(AdderClass.addme(15,21));//ambiguity } }
Output:
OverloadingSampleTest.java:7: error: method addme(int,int) is already defined in class AdderClass static double addme(int a,int b){ ^ 1 error
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
class MainMethodOverloading{ public static void main(){ System.out.println("main without args"); } public static void main(String[] args){ System.out.println("main with String[]"); } public static void main(String args){ System.out.println("main with String"); } }
Output:
main with String[] Press any key to continue . . .