Method overloading is the way of using polymorphism inside a class. We can have two or more methods inside the same class, with different input parameters.
Difference of input parameters can be either:
Let's take a look at them separately (These examples in java, as I am more familiar with it - Sorry about that):
Number of Parameters
public class Mathematics {
public int add (int a, int b) {
return (a + b);
}
public int add (int a, int b, int c) {
return (a + b + c);
}
public int add (int a, int b, int c, int c) {
return (a + b + c + d);
}
}
Look carefully, you can see the method's return type is the same - int
, but theree of these methods having different number of inputs. This is called as method over loading with different number of parameters.
PS: This is a just an example, there's no need to define add functions like this.
Type of parameters
public class Mathematics {
public void display (int a) {
System.out.println("" + a);
}
public void display (double a) {
System.out.println("" + a);
}
public void display (float a) {
System.out.println("" + a);
}
}
Note that every method has the same name and same return type, while they have different input data types.
PS: This example is only for explaining purpose only.
Order of the parameters
public class Mathematics {
public void display (int a, double b) {
System.out.println("Numbers are " + a + " and " + b);
}
public void display (double a, int b) {
System.out.println("Numbers are " + a + " and " + b);
}
}
PS: This example is also for explaining purpose only.