0
0
Kotlinprogramming~5 mins

Overriding methods with override in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Overriding methods with override
O(n)
Understanding Time Complexity

We want to see how the time it takes to run code changes when we use method overriding in Kotlin.

Specifically, how does calling an overridden method affect the work done as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

open class Animal {
    open fun makeSound() {
        println("Some sound")
    }
}

class Dog : Animal() {
    override fun makeSound() {
        println("Bark")
    }
}

fun playSounds(animals: List<Animal>) {
    for (animal in animals) {
        animal.makeSound()
    }
}

This code defines a base class with a method, overrides it in a subclass, and calls the method on a list of animals.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling makeSound() on each animal in the list.
  • How many times: Once for each animal in the list, so as many times as the list size.
How Execution Grows With Input

Each animal in the list causes one method call. So if the list doubles, the calls double too.

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

Pattern observation: The work grows directly with the number of animals.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of animals.

Common Mistake

[X] Wrong: "Overriding methods makes the program slower by a lot because it adds extra work."

[OK] Correct: Overriding just changes which code runs, but calling the method once per item stays the same. The extra work is very small and does not change how the total time grows.

Interview Connect

Understanding how method calls scale helps you explain how your code behaves with more data. This shows you know how object-oriented features affect performance in real situations.

Self-Check

What if makeSound() called another method inside that loops over a list? How would the time complexity change?