Difference between Method overloading and method overriding with example
Method Overloading vs Method Overriding in C#
Method Overloading — Definition:
Method Overloading is a feature in C# where multiple methods can have the same name within the same class but with different parameter lists (different type, number, or order of parameters).
It is also known as:
Compile Time Polymorphism
Static Polymorphism
Early Binding
Method Overriding — Definition:
Method Overriding is a feature in C# where a method in a derived (child) class provides a specific implementation of a method that is already defined in its base (parent) class.
It requires the use of:
virtual
keyword in the base class method
override
keyword in the derived class methodIt is also known as:
Runtime Polymorphism
Dynamic Polymorphism
Late Binding
Feature | Method Overloading | Method Overriding |
---|---|---|
Concept | Same method name, but different parameters (compile-time polymorphism) | Same method name, same parameters, but different implementation in derived class (runtime polymorphism) |
Class Requirement | Same class or base & derived class | Must have inheritance (base & derived class) |
Keywords Used | No keyword needed | virtual in the base class, override in derived class |
Parameters | Must be different (number, type, or order) | It must be exactly the same parameters/signature |
Polymorphism Type | Compile Time Polymorphism | Runtime Polymorphism |
Achieved By | Function Signature Change | Inheritance & overriding base method |
Live Example — Covering all scenarios
Output:
Summary — Key Differences:
Method Overloading | Method Overriding |
---|---|
Same method name but different parameters | Same method name and same parameters |
Compile Time Polymorphism | Runtime Polymorphism |
No inheritance required | Inheritance is mandatory |
Achieved within the same class or derived class | Achieved through virtual & override keywords |
Method signature should differ | Method signature must remain the same |
Pro Tip (Interview Point):
-
Overloading is used to ensure functionality reusability within the same class.
-
Overriding is used for the customized behavior of the base class method in the child class.
Comments
Post a Comment