Let’s break down method overriding and method overloading clearly and compare them. These are concepts in object-oriented programming (OOP), commonly in languages like Java, C++, and C#.
1. Method Overriding
Definition:
Method overriding occurs when a subclass (child class) provides its own implementation of a method that is already defined in its superclass (parent class). The method in the child class must have the same name, parameters, and return type as in the parent class.
Key Points:
- Happens between parent and child classes (inheritance needed).
- Used for runtime polymorphism.
- The method signature must be identical.
- Allows the child class to change or extend the behavior of the parent class method.
Example (Java):
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Output: Dog barks
}
}
✅ Here, Dog
overrides the sound()
method of Animal
.
2. Method Overloading
Definition:
Method overloading occurs when two or more methods in the same class have the same name but different parameters (different number or types of parameters).
Key Points:
- Happens within the same class (can also happen in subclass).
- Used for compile-time (static) polymorphism.
- The method name is the same, but parameter list must differ.
- Return type can be same or different (but just changing return type is not enough).
Example (Java):
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Test {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // Output: 5
System.out.println(calc.add(2.5, 3.5)); // Output: 6.0
System.out.println(calc.add(1, 2, 3)); // Output: 6
}
}
✅ Here, add()
is overloaded with different parameters.
Comparison Table
Feature | Method Overriding | Method Overloading |
---|---|---|
Definition | Child class provides a new implementation of parent class method | Same class has methods with same name but different parameters |
Inheritance | Required | Not required |
Polymorphism Type | Runtime (Dynamic) | Compile-time (Static) |
Method Signature | Must be same | Must be different |
Return Type | Same or covariant | Can be same or different |
Access Modifier | Can’t be more restrictive than parent | Any |
Example | sound() in Animal and Dog | add(int, int) and add(double, double) |