Overloading in Java
Overloading in Java
Overloading allows different methods to have the same name, but different signatures
where the signature can differ by the number of input parameters or type of input
parameters or both. Overloading is related to compile-time (or static) polymorphism.
// overloading in Java.
{
return (x + y);
}
{
return (x + y + z);
}
{
return (x + y);
}
{
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10.5, 20.5));
}
Output :
30
60
31.0
Question Arises:
Q. What if the exact prototype does not match with arguments.
Ans.
Priority wise, compiler take these steps:
1. Type Conversion but to higher type(in terms of range) in same family.
2. Type conversion to next higher family(suppose if there is no long data type
available for an int data type, then it will search for the float data type).
Let’s take an example to clear the concept:-
class Demo {
{
}
{
}
{
}
}
class UseDemo {
{
byte a = 25;
obj.show(a); // it will go to
obj.show("hello"); // String
obj.show(250); // Int
obj.show("A"); // String
// will be an error.
}
What is the advantage?
We don’t have to create and remember different names for functions doing the same
thing. For example, in our code, if overloading was not supported by Java, we would
have to create method names like sum1, sum2, … or sum2Int, sum3Int, … etc.
{
}
However, Overloading methods on return type are possible in cases where the data type
of the function being called is explicitly specified. Look at the examples below :
{
System.out.println(foo(1));
System.out.println(foo(1, 2));
}
Output:
10
a
class A {
{
System.out.println(a.foo(1));
System.out.println(a.foo(1, 2));
}
Output:
10
a
Can we overload static methods?
The answer is ‘Yes’. We can have two ore more static methods with same name, but
differences in input parameters. For example, consider the following Java program.
Refer this for details.
Can we overload methods that differ only by static keyword?
We cannot overload two methods in Java if they differ only by static keyword (number
of parameters and types of parameters is same). See following Java program for example.
Refer this for details.
Can we overload main() in Java?
Like other static methods, we can overload main() in Java. Refer overloading main() in
Java for more details.
// A Java program with overloaded main()
import java.io.*;
{
Test.main("Geek");
}
{
}
}
Output :
Hi Geek (from main)
Hi, Geek
Hi, Dear Geek, My Geek
Does Java support Operator Overloading?
Unlike C++, Java doesn’t allow user-defined overloaded operators. Internally Java
overloads operators, for example, + is overloaded for concatenation.
What is the difference between Overloading and Overriding?
Overloading is about same function have different signatures. Overriding is about
same function, same signature but different classes connected through inheritance.