Sobes.tech
Junior — Middle

How to distinguish between method overloading and method overriding in object-oriented programming?

sobes.tech AI

Answer from AI

Method overloading is the definition of multiple methods with the same name but different parameters (types or number) within a single class. It allows calling a method with different sets of arguments.

Method overriding is the modification of a method's implementation inherited from a parent class in a child class while maintaining the same signature (name and parameters).

Example in JavaScript (Node.js) — JavaScript does not have traditional overloading, but it can be simulated:

class Example {
  method(x) {
    if (typeof x === 'number') {
      return x * 2;
    } else if (typeof x === 'string') {
      return x + x;
    }
  }
}

class ChildExample extends Example {
  method(x) { // overriding
    return super.method(x) + '!';
  }
}

Here, method is overloaded by parameter type (simulation), and overridden in the child class to change behavior.