This article is part of an interview question series that includes various topics with explanations and possible questions based on the topic. This article explains the concept of method overloading and method overriding.
Method overloading
Having methods of the same name and different signatures in scope, or we can say in a class, is known as method overloading. The unique signature of a method indicates that either it has a different number of parameters or different data types of parameters.
So, a question might arise, which is how does the class distinguish the methods with the same name? It is distinguished by the method signature.
Purpose of method overloading
- Increases the readability of the code, as different methods performing the same action can have the same name but a different number of arguments or different types of arguments
- To achieve compile-time polymorphism.
Example
- using system;
- class VariousAreas {
- public static void area(int x, int y){
- console.WriteLine(“Area of rectangle: ”, x*y);
- }
- public static void area(double x, int y){
- console.WriteLine(“Area of rectangle with type double: ”, x*y );
- }
- Public static void area(int x){
- console.WriteLine(“Area of Square: ”, x*x)
- }
- Public static void area(double x){
- console.WriteLine(“Area of square with type double: ”, x*x );
- }
- Static void main(string[] args){
- Area(5);
- Area(4.5, 10);
- Area(2, 8);
- Area(2.5);
- }
- }
Output
Area of Square: 25
Area of rectangle with type double: 45
Area of rectangle: 16
Area of square with type double: 6.25
Method Overriding
Having two or more methods with the same name and signature as method in the parent class is known as method overriding. Method overriding allows us to invoke functions from base class to derived class. So, we can also say that a technique that includes creating a method in the derived class that has the same name and signature as the method in the base class is known as method overriding.
Method overriding is a way by which we can achieve run time polymorphism. Both the override method and the virtual method must have the same access level modifier.
Purpose of method overriding
- To achieve run time polymorphism.
- To change the existing functionalities.
Example


Join the conversation! Your thoughts help the community grow.