Overriding methods with override in Kotlin - Time & Space 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?
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 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.
Each animal in the list causes one method call. So if the list doubles, the calls double too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The work grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of animals.
[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.
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.
What if makeSound() called another method inside that loops over a list? How would the time complexity change?