Abstract methods in Typescript - Time & Space Complexity
We want to understand how using abstract methods affects the time it takes for a program to run.
Specifically, we ask: how does calling abstract methods impact the number of steps as input grows?
Analyze the time complexity of the following code snippet.
abstract class Shape {
abstract area(): number;
}
class Square extends Shape {
constructor(private side: number) { super(); }
area() { return this.side * this.side; }
}
const squares: Square[] = [new Square(2), new Square(3), new Square(4)];
for (const sq of squares) {
console.log(sq.area());
}
This code defines an abstract method area and calls it on several objects in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
areamethod on each object in the array. - How many times: Once for each object in the
squaresarray.
Each time we add one more square, we call area one more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to area |
| 100 | 100 calls to area |
| 1000 | 1000 calls to area |
Pattern observation: The number of operations grows directly with the number of objects.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of objects increases.
[X] Wrong: "Abstract methods slow down the program because they add extra steps."
[OK] Correct: Calling an abstract method is just like calling any other method; the time depends on how many times you call it, not on it being abstract.
Understanding how abstract methods affect performance helps you explain design choices clearly and confidently in interviews.
"What if the area method itself contained a loop over a large array? How would the time complexity change?"