0
0
Kotlinprogramming~5 mins

Abstract classes and methods in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Abstract classes and methods
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the number of shapes increases, the program calls the area() method more times, one per shape.

Input Size (n)Approx. Operations
1010 calls to area()
100100 calls to area()
10001000 calls to area()

Pattern observation: The number of operations grows directly with the number of shapes.

Final Time Complexity

Time Complexity: O(n)

This means the time to compute total area grows in a straight line with the number of shapes.

Common Mistake

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

Interview Connect

Understanding how abstract methods affect time helps you explain design choices clearly and shows you know how code structure relates to performance.

Self-Check

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?