What is the difference between method overloading and method overriding?
Method overloading and method overriding are both concepts in object-oriented programming, but they serve different purposes and involve different aspects of method behavior. Here's a breakdown of the differences between method overloading and method overriding:
1.
Method Overloading:
Method overloading occurs when multiple methods within the same class (or a derived class) have the same name but different parameter lists. The parameters can differ in terms of number, order, or type.
Key points about method overloading:
-
Overloaded methods are differentiated based on their parameter lists.
- Overloading doesn't require inheritance; it can occur within the same class or derived classes.
- Overloaded methods have the same or different return types.
- Overloading is determined at compile-time based on the arguments passed to the method.
- It can be executed both within the class itself and within its derived child class as well.
- This is used to implement static polymorphism.
Example:
class Calculator {
public int Add(int a, int b) {
return a + b;
}
public double Add(double a, double b) {
return a + b;
}
}
2. Method Overriding:
Method overriding involves providing a new implementation for a method in a derived class that has the same signature (name, return type, and parameters) as a method in the base class. It allows a subclass to provide its own behavior while maintaining a common interface with the base class.
Key points about method overriding:
-
Overridden methods must have the same name, return type, and parameters as the base class method.
- Method overriding is used to achieve runtime polymorphism, where the method called is determined by the actual type of the object at runtime.
- Overriding requires inheritance; overridden methods exist in the base class and are redefined in derived classes using the 'override' keyword.
- The 'virtual' keyword is used in the base class to indicate that a method can be overridden.
- It is not executable within the class itself; It must come under inheritance, involving both child and parent classes.
Example:
class Shape {
public virtual void Draw() {
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape {
public override void Draw() {
Console.WriteLine("Drawing a circle");
}
}
In summary, method overloading allows you to define multiple methods with the same name but different parameter lists, providing versatility and convenience for method calls. Method overriding, on the other hand, involves redefining a base class method in a derived class to provide a new implementation, enabling polymorphism and dynamic method dispatch.