Abstract classes in Typescript - Time & Space Complexity
We want to understand how the time it takes to run code with abstract classes changes as the input grows.
Specifically, how does using abstract classes affect the number of steps the program takes?
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; }
}
function totalArea(shapes: Shape[]): number {
let sum = 0;
for (const shape of shapes) {
sum += shape.area();
}
return sum;
}
This code defines an abstract class and calculates the total area of many shapes by calling their area method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of shapes and calling
area()on each. - How many times: Once for each shape in the input array.
Each shape requires one call to area(), so the total steps grow directly with the number of shapes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to area() and 10 loop steps |
| 100 | 100 calls to area() and 100 loop steps |
| 1000 | 1000 calls to area() and 1000 loop steps |
Pattern observation: The work grows evenly as the number of shapes increases.
Time Complexity: O(n)
This means the time to calculate total area grows in a straight line with the number of shapes.
[X] Wrong: "Using abstract classes makes the code slower because of extra overhead."
[OK] Correct: The abstract class itself does not add extra loops or repeated work; it just defines a structure. The main cost depends on how many shapes you process.
Understanding how abstract classes affect time helps you explain design choices clearly and shows you know how structure relates to performance.
"What if each shape's area() method did a complex calculation with its own loops? How would the time complexity change?"