Mark As Completed Discussion

Overriding vs Overloading

When it comes to inheritance, there are two ways to add methods to your subclasses. Overriding a class means altering a method from its superclass. Overloading a method means creating a separate method with the same name but different parameter types.

Overriding must occur between the superclass and subclass. On the other hand, function overloading can occur in the same class.

When comparing overloading and overriding, the function signature is the primary difference. A function signature contains both the name of the function and the parameters of the function. If the function signature is identical for two classes in an inheritance hierarchy, then you are overriding a method. If they are different (even in the same class), then you are overloading the method.

1class A {
2    aMethod(a, b) {
3        if (typeof a === 'number' && typeof b === 'number') {
4            return a.toString() + b.toString();
5        } else if (typeof a === 'number' && typeof b === 'string') {
6            return a.toString() + b;
7        } else if (typeof a === 'string' && typeof b === 'number') {
8            return a + b.toString();
9        }
10    }
11}
12
13class B extends A {
14    aMethod(a, b) {
15        if (typeof a === 'number' && typeof b === 'number') {
16            return (a + b).toString();
17        } else if (typeof a === 'string' && typeof b === 'number') {
18            return super.aMethod(a, b);
19        } else if (typeof a === 'number' && typeof b === 'string') {
20            return super.aMethod(a, b);
21        } else if (typeof a === 'number' && typeof b === 'number') {
22            return (a + b).toString();
23        }
24    }
25}

Note: Go doesn't support method overloading. To demonstrate a similar concept, we use different method names based on the parameter types.