Method Overloading
suggest changeMethod overloading, also known as function overloading, is the ability of a class to have multiple methods with the same name, granted that they differ in either number or type of arguments.
Compiler checks method signature for method overloading.
A method signature consists of three things:
- Method name
- Number of parameters
- Types of parameters
If these three are the same for any two methods in a class, the compiler reports a duplicate method.
This type of polymorphism is called static or compile time polymorphism because the appropriate method to be called is decided by the compiler during the compile time based on the argument list.
class Polymorph {
public int add(int a, int b){
return a + b;
}
public int add(int a, int b, int c){
return a + b + c;
}
public float add(float a, float b){
return a + b;
}
public static void main(String... args){
Polymorph poly = new Polymorph();
int a = 1, b = 2, c = 3;
float d = 1.5f, e = 2.5f;
System.out.println(poly.add(a, b));
System.out.println(poly.add(a, b, c));
System.out.println(poly.add(d, e));
}
}
This will result in:
2
6
4.0
Overloaded methods may be static or non-static. That does not affect method overloading.
public class Polymorph {
private static void methodOverloaded()
{
//No argument, private static method
}
private int methodOverloaded(int i)
{
//One argument private non-static method
return i;
}
static int methodOverloaded(double d)
{
//static Method
return 0;
}
public void methodOverloaded(int i, double d)
{
//Public non-static Method
}
}
Changing only the return type is not method overloading. The two declarations below have the same signature and cannot be declared in one class.
public class Polymorph {
void methodOverloaded(){
//No argument and No return type
}
int methodOverloaded(){
//No argument and int return type
return 0;
}