Method Overloading and Overriding

Method overloading and method overriding are two fundamental concepts in object-oriented programming, often used in languages like Java, C++, and C#. Here’s an explanation of each:

Method Overloading:

Method overloading allows a class to have multiple methods with the same name but different parameters. These methods can perform similar or different tasks based on the parameters passed to them. Overloading is determined by the number, types, and order of parameters in the methods.

Key Points:

  1. Methods must have the same name but different parameter lists (type, number, or order of parameters).
  2. Overloading occurs in the same class or in a subclass.
  3. Return type alone doesn’t differentiate overloaded methods.
  4. Overloaded methods are resolved at compile time based on the method signature.

Example (Java):

public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {
return a + b;
}
}

Method Overriding:

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method signature (name, parameters, return type) must be the same in both the superclass and subclass. This allows the subclass to define its behavior for the method, providing more specialized functionality.

Key Points:

  1. Method overriding occurs in a subclass that extends a superclass.
  2. The method signature (name, parameters, return type) must be the same in both superclass and subclass.
  3. Overriding is used to provide a specific implementation of a method in the subclass.
  4. The overridden method in the subclass must have the same or wider access modifier as the method in the superclass.
  5. Overriding is resolved at runtime based on the actual object type.

Example (Java):

class Animal {
void makeSound() {
System.out.println(“Some sound”);
}
}

class Dog extends Animal {
@Override
void makeSound() {
System.out.println(“Bark”);
}
}

Leave a Reply