Inheritance using classes in Javascript - Time & Space Complexity
When using inheritance with classes, we want to know how the program's work grows as we create more objects or call methods.
We ask: How does the time to run change when we use inherited methods or create many instances?
Analyze the time complexity of the following code snippet.
class Animal {
speak() {
console.log('Animal speaks');
}
}
class Dog extends Animal {
speak() {
super.speak();
console.log('Dog barks');
}
}
const dog = new Dog();
dog.speak();
This code shows a Dog class inheriting from Animal and calling the parent method before adding its own behavior.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
speakmethod on the Dog instance. - How many times: Once per call; no loops or recursion inside the methods.
Each time we call speak, it runs a fixed number of steps: one call to the parent method and one extra log.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 2 (one parent call + one child log) |
| 10 | 20 (10 calls x 2 operations each) |
| 100 | 200 (100 calls x 2 operations each) |
Pattern observation: The work grows directly with how many times we call the method, staying simple and linear.
Time Complexity: O(n)
This means the time grows in a straight line with the number of method calls; each call takes a fixed amount of work.
[X] Wrong: "Inheritance makes method calls slower exponentially because of chaining."
[OK] Correct: Each inherited method call adds only a fixed small number of steps, so time grows linearly, not exponentially.
Understanding how inheritance affects time helps you explain code efficiency clearly and shows you know how objects work behind the scenes.
"What if the speak method called itself recursively? How would the time complexity change?"