0
0
Javascriptprogramming~5 mins

Method overriding in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overriding
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
11 method call
1010 method calls if called on 10 objects
100100 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.

Final Time Complexity

Time Complexity: O(1)

This means calling an overridden method takes a fixed amount of time each call, regardless of class hierarchy size.

Common Mistake

[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.

Interview Connect

Understanding that method overriding does not add hidden time costs helps you explain how object-oriented features work efficiently in real code.

Self-Check

"What if the overridden method calls the parent method inside it? How would the time complexity change?"