Method overloading
Methods of the same name can be declared in the same
class, as long as they have different sets of parameters
(determined by the number, types and order of the
parameters) this is called method overloading.
When an overloaded method is called, the Java compiler
selects the appropriate method by examining the
number, types and order of the arguments in the call.
Method overloading is commonly used to create several
methods with the same name that perform the same or
similar tasks, but on different types or different numbers
of arguments.
Method Overloadin
g
tMyn
For example, Math methods abs, min and max are
overloaded with four versions each:
1. One with two double parameters.
2. One with two float parameters.
3. One with two int parameters.
4. One with two long parameters.
Method Overloadin
g
tMyn
package Timosoft;
public class Overloading
{
int square(int intVal)
{
[Link]("Called square with argument: "+intVal);
return intVal*intVal;
}
double square(double doubleVal)
{
[Link]("Called square with argument: "+doubleVal);
return doubleVal*doubleVal;
}
}
Method Overloadin
g
tMyn
package Timosoft;
public class OverloadingTest
{
public static void main(String[] args)
{
Overloading first=new Overloading();
[Link]("Square of integer 8 equals to "+[Link](8));
[Link]("Square of double 8.5 equals to "+[Link](8.5));
}
}
run:
Called square with argument: 8
Square of integer 8 equals to 64
Called square with argument: 8.5
Square of double 8.5 equals to 72.25
BUILD SUCCESSFUL (total time: 3 seconds)
Method Overloadin
g
tMyn
The compiler distinguishes overloaded methods by their
signature a combination of the methods name and the
number, types and order of its parameters.
If the compiler looked only at method names during
compilation, the code in previous example would be
ambiguous.
Internally, the compiler uses longer method names that
include the original method name, the types of each
parameter and the exact order of the parameters to
determine whether the methods in a class are unique in
that class.
Overloaded method calls cannot be distinguished by
return type.
Method Overloadin
g
tMyn
Overloaded method declarations with identical
signatures cause compilation errors, even if the return
types are different.
That is understandable, because the return type is not
necessarily apparent when you call a method.
Method Overloadin
g
tMyn