Difference between Method Overloading vs Method overriding:
- Overloading can occur without inheritance. Overriding of functions occurs when one class is inherited from another class.
- Overloaded functions must differ in function signature i.e. either number of parameters or type of parameters should differ. In overriding, function signatures must be same.
- Overloaded functions are in same scope; whereas Overridden functions are in different scopes.
|
Method Overloading |
Method Overriding |
| Definition |
In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order. |
In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class. |
| Meaning |
Method Overloading means more than one method shares the same name in the class but having different signature. |
Method Overriding means method of base class is re-defined in the derived class having same signature. |
| Behavior |
Method Overloading is to “add” or “extend” more to method’s behavior. |
Method Overriding is to “Change” existing behavior of method. |
| Polymorphism |
It is a compile time polymorphism. |
It is a run time polymorphism. |
| Inheritance |
It may or may not need inheritance in Method Overloading. |
It always requires inheritance in Method Overriding. |
| Signature |
In Method Overloading, methods must have different signature. |
In Method Overriding, methods must have same signature. |
| Relationship of Methods |
In Method Overloading, relationship is there between methods of same class. |
In Method Overriding, relationship is there between methods of super class and sub class. |
| Criteria |
In Method Overloading, methods have same name different signatures but in the same class. |
In Method Overriding, methods have same name and same signature but in the different class. |
| No. of Classes |
Method Overloading does not require more than one class for overloading. |
Method Overriding requires at least two classes for overriding. |
Diagram to understand exact difference :-
Example in program:-
Method Overloading:
Class Add
{
int sum(int a, int b)
{
return a + b;
}
int sum(int a)
{
return a + 10;
}
}
Method Overriding:
Class A // Super Class
{
void display(int num)
{
print num ;
}
}
//Class B inherits Class A
Class B //Sub Class
{
void display(int num)
{
print num ;
}
}