Method overriding in Javascript - Time & Space Complexity
We want to understand how the time it takes to run code changes when we use method overriding in JavaScript.
Specifically, how does calling an overridden method affect the work done as the program runs?
Analyze the time complexity of the following code snippet.
class Animal {
speak() {
console.log('Animal speaks');
}
}
class Dog extends Animal {
speak() {
console.log('Dog barks');
}
}
const pet = new Dog();
pet.speak();
This code shows a class Dog overriding the speak method from its parent Animal class, then calling the overridden method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single method call to
speak(). - How many times: The method is called once in this example.
Since the method call happens once, the work done stays the same no matter how many objects or classes exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 method call |
| 10 | 10 method calls if called on 10 objects |
| 100 | 100 method calls if called on 100 objects |
Pattern observation: The time grows directly with how many times the method is called, not with the complexity of overriding itself.
Time Complexity: O(1)
This means calling an overridden method takes a fixed amount of time each call, regardless of class hierarchy size.
[X] Wrong: "Overriding a method makes the program slower as the class hierarchy grows."
[OK] Correct: The method call itself runs in constant time; the class hierarchy size does not add extra steps during the call.
Understanding that method overriding does not add hidden time costs helps you explain how object-oriented features work efficiently in real code.
"What if the overridden method calls the parent method inside it? How would the time complexity change?"