Method overriding with types in Typescript - Time & Space Complexity
We want to understand how the time it takes to run code changes when using method overriding with types in TypeScript.
Specifically, we ask: how does the program's work grow as input or calls increase?
Analyze the time complexity of the following code snippet.
class Animal {
speak(): string {
return "...";
}
}
class Dog extends Animal {
speak(): string {
return "Woof!";
}
}
function makeSpeak(animal: Animal) {
return animal.speak();
}
const dog = new Dog();
makeSpeak(dog);
This code shows a base class with a method, a subclass that overrides it, and a function calling the method on an object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
speakmethod on an object. - How many times: Once per call to
makeSpeak. No loops or recursion here.
Since there is no loop or repeated calls inside the snippet, the work grows directly with how many times makeSpeak is called.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The time grows linearly with the number of calls.
Time Complexity: O(n)
This means if you call the method n times, the total work grows roughly in direct proportion to n.
[X] Wrong: "Overriding a method makes the program slower by adding hidden loops or extra work."
[OK] Correct: Overriding just changes which code runs when the method is called. It does not add loops or repeated work by itself.
Understanding how method calls and overriding affect performance helps you explain code behavior clearly and confidently in interviews.
"What if the speak method called itself recursively? How would the time complexity change?"