Abstract classes and methods in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code using abstract classes and methods changes as the input grows.
Specifically, we ask: how does using abstract methods affect the speed of running a program?
Analyze the time complexity of the following code snippet.
abstract class Shape {
abstract fun area(): Double
}
class Circle(val radius: Double) : Shape() {
override fun area() = 3.14 * radius * radius
}
fun totalArea(shapes: List<Shape>): Double {
var sum = 0.0
for (shape in shapes) {
sum += shape.area()
}
return sum
}
This code defines an abstract class with an abstract method, then calculates the total area of many shapes by calling the method on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of shapes and calling the
area()method on each. - How many times: Once for each shape in the list (n times if the list has n shapes).
As the number of shapes increases, the program calls the area() method more times, one per shape.
| 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 shapes.
Time Complexity: O(n)
This means the time to compute total area grows in a straight line with the number of shapes.
[X] Wrong: "Using abstract methods makes the program slower by a lot because of extra overhead."
[OK] Correct: Calling abstract methods adds only a tiny fixed cost per call, so the overall time still grows mainly with the number of shapes, not the method type.
Understanding how abstract methods affect time helps you explain design choices clearly and shows you know how code structure relates to performance.
What if we added a nested loop inside the area() method that runs proportional to the size of some input? How would the time complexity change?